问题
我有一个包含 if 语句的方法:
- private void ValidateInputs()
- {
- if (txtBox_eventName.Text.Trim() == string.Empty)
- {
- MessageBox.Show("Please enter a valid event name", "Action Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
- txtBox_eventName.Focus();
- return;
- }
- if (nud_noOfGuests.Value < 10 || nud_noOfGuests.Value > 200)
- {
- MessageBox.Show("Please enter no of guests between 10 and 200", "Action Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- if (radBtn_primeRib.Checked == false && radBtn_chickenMarsala.Checked == false && radBtn_gardenLasagna.Checked == false)
- {
- MessageBox.Show("Please make an Entree choice", "Action Reuired", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return;
- }
- }
复制代码
我有第二种方法可以做其他事情。我在点击事件中调用这两种方法。如果满足第一种方法中的任何 if 条件,我想停止程序执行第二种方法。
我调用这两种方法的点击事件是:
- private void btn_createEvent_Click(object sender, EventArgs e)
- {
- ValidateInputs();
- SetValues();
- calcCharges = new CateringEvent(eventName, noOfGuests, selectedEntre, barOption, wineOption);
- lbl_calcEntreCharges.Text = calcCharges.EntreCharge.ToString("C2");
- lbl_calcDrinkCharges.Text = calcCharges.DrinksCharge.ToString("C2");
- lbl_calcSurcharge.Text = calcCharges.Surcharge.ToString("C2");
- lbl_calcTotalCharges.Text = calcCharges.TotalCharge.ToString("C2");
- txtBox_eventName.Enabled = false;
- btn_createEvent.Enabled = false;
- btn_modifyEvent.Enabled = true;
- }
复制代码
我希望 ValidateInputs() 仅在 SetValues() 中的 if 条件都不起作用时运行。在这种情况下,我怎样才能做到这一点?
回答
您只需要将 ValidateInputs 方法的返回类型更改为 bool。
- private bool ValidateInputs()
- {
- if (txtBox_eventName.Text.Trim() == string.Empty)
- {
- MessageBox.Show("Please enter a valid event name", "Action Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
- txtBox_eventName.Focus();
- return false;
- }
- if (nud_noOfGuests.Value < 10 || nud_noOfGuests.Value > 200)
- {
- MessageBox.Show("Please enter no of guests between 10 and 200", "Action Required", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return false;
- }
- if (radBtn_primeRib.Checked == false && radBtn_chickenMarsala.Checked == false && radBtn_gardenLasagna.Checked == false)
- {
- MessageBox.Show("Please make an Entree choice", "Action Reuired", MessageBoxButtons.OK, MessageBoxIcon.Error);
- return false;
- }
- return true;
- }
复制代码
然后将点击方法更改为:
- if (ValidateInputs() == false) // or if(!ValidateInputs())
- return;
- SetValues();
复制代码
|