2017-03-07 29 views
-1

我想对我的程序执行一些错误检查。 如果没有选择属性,我的程序应该抛出一条错误消息,指示用户输入缺少的信息。 我已经实现了一些属性,但处理单选按钮和布尔的最后一部分是造成我的麻烦。使用bool和单选按钮检查错误

private void btnAddPatient_Click(object sender, RoutedEventArgs e)////Adds Patients using buttone etc to set properties 
    { 
     string name = txtPatientName.Text,bloodType; 
     int x=1;   
     DateTime dob; 
     bool bloodA = rbA.IsChecked.Equals(true); 
     bool bloodB = rbB.IsChecked.Equals(true); 
     bool bloodAB = rbAB.IsChecked.Equals(true); 
     bool blood0 = rb0.IsChecked.Equals(true); 



     if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || rbA.IsChecked.Equals(false) || rbB.IsChecked.Equals(false) || rbAB.IsChecked.Equals(false) || rb0.IsChecked.Equals(false)) 
     { 

      if (txtPatientName.Text == "") 
      { 
       MessageBox.Show("Please enter Patient's Name"); 
      } 

      else if (dpDOB.SelectedDate == null) 
      { 
       MessageBox.Show("Please select a date"); 
      } 


      else if (rbA.IsChecked.Equals(false) || rbB.IsChecked.Equals(false) || rbAB.IsChecked.Equals(false) || rb0.IsChecked.Equals(false)) 
      { 
       MessageBox.Show("Please enter patient's blood type"); 

      } 

     } 

     else 
     { 
      if (bloodA) 
      { 
       bloodType = "A"; 
      } 
      else if (bloodB) 
      { 
       bloodType = "B"; 
      } 
      else if (bloodAB) 
      { 
       bloodType = "AB"; 
      } 

      else 
      { 
       bloodType = "0"; 
      } 


      dob = dpDOB.SelectedDate.Value; 

      Patient patient = new Patient(name, bloodType, x, dob); 

      MainWindow mainWindow = Owner as MainWindow; 

      patients.Add(patient); 
      lstPatients.ItemsSource = null; 
      lstPatients.ItemsSource = patients; 
      // this.Close(); 
     } 
    } 
+2

你有什么烦恼到底是什么? –

+0

即使我检查其中一个单选按钮,代码也不会移动到属性被赋值等的else语句中。 –

+0

是的。您的代码表示如果其中一个单选按钮没有选中,请发送警告 –

回答

1

你已经得到的血液#变量捕获的值,所以您可以使用这些方法之一:

使用变量您的if语句:

if (!(bloodA || bloodB || bloodAB || blood0)) 
    MessageBox.Show("Please enter patient's blood type"); 

使用列表(只是多了一个行):

List<bool> rbValues = new List<bool>() { bloodA, bloodB, bloodAB, blood0 }; 
if (!rbValues.Any(b => b)) 
    MessageBox.Show("Please enter patient's blood type"); 

或者使其可重复使用的方法中,当你使用它˚F或其他评价:

var anyBlood = (bloodA || bloodB || bloodAB || blood0) 

... 
if (dpDOB.SelectedDate == null || txtPatientName.Text == "" || !anyBlood) 
... 
    if (!anyBlood) 
     MessageBox.Show("Please enter patient's blood type"); 

希望它可以帮助

+0

非常感谢,第一个答案完成了这项工作。谢谢!!! –