我希望我的while循环使用一个消息框最多问5次问题。
当我运行它时,我会问一次,当我选择“是”时,会打开5个新表格。
如何修复此循环,以防止消息框询问用户是或不超过5次,以及如何防止在我选择一次后打开5个表单?
我的代码
private void btnNext_Click(object sender, EventArgs e)
{
int maxAddDriver = 5;
int addDriver = 0;
DialogResult answer = MessageBox.Show("Would you like to add an additional driver to policy?", "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
Hide();
while (addDriver < maxAddDriver && answer == DialogResult.Yes)
{
addDriver++;
Hide();
new frmAdditionalDriver().Show();
//answer = MessageBox.Show("Would you like to add an additional driver to policy?",
// "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
}
new frmInsurancePolicy().ShowDialog();
Show();
}
答案 0 :(得分:0)
请尝试以下操作: 将maxAddDriver和addDriver移到按钮单击之外,这样就不会在每次单击按钮时重置它们,并保留以前的单击计数。
int maxAddDriver = 5;
int addDriver = 0;
private void btnNext_Click(object sender, EventArgs e)
{
// already displayed message box 5 times, so just display insurance policy dialog
if (this.addDriver == this.maxAddDriver)
{
new frmInsurancePolicy().ShowDialog();
}
var answer = MessageBox.Show("Would you like to add an additional driver to policy?", "Info",
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
Hide();
this.addDriver++;
if (answer == DialogResult.Yes && this.addDriver < this.maxAddDriver)
{
new frmAdditionalDriver().Show();
}
Show();
}