【问题标题】:error checking using bool and radiobuttons使用 bool 和单选按钮进行错误检查
【发布时间】:2017-03-07 22:27:16
【问题描述】:

我想对我的程序进行一些错误检查。 如果没有选择属性,我的程序应该会抛出一条错误消息,指示用户输入缺失的信息。 我已经为一些属性实现了这个,但处理单选按钮和布尔值的最后部分给我带来了麻烦。

 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();
        }
    }

【问题讨论】:

  • 你到底遇到了什么麻烦?
  • 即使我选中其中一个单选按钮,代码也不会转到分配属性等的 else 语句。
  • 是的。您的代码说,如果未选中其中一个单选按钮,请发送警告

标签: c# wpf xaml boolean


【解决方案1】:

您已经获得了 blood# 变量中捕获的值,因此您可以使用以下方法之一:

在 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");

或者让它在你的方法中可重用,因为你将它用于其他评估:

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

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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-29
    • 2018-06-28
    • 2018-06-23
    • 2016-02-15
    • 1970-01-01
    • 2014-02-05
    • 2013-09-29
    • 2012-03-18
    相关资源
    最近更新 更多