2016-04-25 99 views
0

所以我有多个不同的单选按钮,在不同的组框中。在用户能够“保存”他们的表单之前,需要填写所有字段。所以我试图确保所有单选按钮都已填充。此刻,我正尝试使用以下代码:WinForms中的单选按钮验证

if (!(this.RoundTrip.Checked || this.OneWay.Checked)) 
      { 
       MessageBox.Show("Select an option for Trip Type"); 


       if (!(this.NorthRad.Checked || this.ExpressRad.Checked || this.ExpressRad.Checked)) 
       { 
        MessageBox.Show("Select an Option for Route Type"); 

       } 
       if (!(this.YesNeeded.Checked || this.NotNeeded.Checked)) 
       { 
        MessageBox.Show("Select an option for accessibility"); 

       } 
       if (this.AdultNum.Value == 0 && this.SeniorNum.Value == 0 && this.ChildNum.Value == 0) 
       { 
        MessageBox.Show("Select at least one ticket"); 

       } 
       return; 
      } 

与此代码,它不允许我点击保存按钮,但没有消息框出现。即使在我填写收音机框后,我也无法点击保存按钮。任何帮助,将不胜感激。

回答

0

你的逻辑似乎是正确的,但它总是会在最后一行返回。也许你需要的是这样的东西;

private void btnSave_Clicked() 
    { 
     if (!IsValidDataEntered()) return; 

     Save(); 
    } 

    private bool IsValidDataEntered() 
    { 
     if (!(this.RoundTrip.Checked || this.OneWay.Checked)) 
      MessageBox.Show("Select an option for Trip Type"); 

     else if (!(this.NorthRad.Checked || this.ExpressRad.Checked || this.ExpressRad.Checked)) 
      MessageBox.Show("Select an Option for Route Type"); 

     else if (!(this.YesNeeded.Checked || this.NotNeeded.Checked)) 
      MessageBox.Show("Select an option for accessibility"); 

     else if (this.AdultNum.Value == 0 && this.SeniorNum.Value == 0 && 
       this.ChildNum.Value == 0) 
      MessageBox.Show("Select at least one ticket"); 

     else 
      return true; 

     return false; 
    } 
0

如果您正在验证没有选择,那么您需要使用& &而非||。

如果没有选项被选中,您需要验证是否没有选中单选按钮。使用OR,如果第一个逻辑检查满足条件,那么它不会检查第二个。同样在你的情况下,假设没有其他的单选按钮说N/A或者什么的,你的内部语句将永远是真的,因为至少一个单选按钮将不会被检查,如果另一个被选中。

0

我怀疑是顶级if导致问题的条件,其他条件不会评估为顶级条件可能是true在您的测试。

你需要大概是什么...

if (!(this.RoundTrip.Checked || this.OneWay.Checked)) 
{ 
    MessageBox.Show("Select an option for Trip Type"); 
} 
else if (!(this.NorthRad.Checked || this.ExpressRad.Checked || this.ExpressRad.Checked)) 
{ 
    MessageBox.Show("Select an Option for Route Type"); 

} 
else if (!(this.YesNeeded.Checked || this.NotNeeded.Checked)) 
{ 
    MessageBox.Show("Select an option for accessibility"); 

} 
else if (this.AdultNum.Value == 0 && this.SeniorNum.Value == 0 && this.ChildNum.Value == 0) 
{ 
    MessageBox.Show("Select at least one ticket"); 
} 
return; 

另注,因为你有groupbox进行分组,你可以使用简单的Linq来评估组。

var group1Validation = GroupBox1.Controls 
          .OfType<RadioButton>() 
          .Any(r=>r.Checked); 


var group2Validation = GroupBox2.Controls 
          .OfType<RadioButton>() 
          .Any(r=>r.Checked); 


if(!group1) 
{ 
    MessageBox.Show("Select an option for Trip Type"); 
    ... 
}