比较多个if语句中的多个列表框

时间:2017-04-09 18:40:01

标签: c# button textbox listbox

这里的提交按钮应该检查输入到文本框中的答案是否与列表框中的正确答案匹配,除了列表框(每个'主题' )。如何让它适用于这两种类型的问题,而不会在第二种类型上出错(在这种情况下,它是第二种if语句的错误)?注释掉的部分是我尝试做的第二种方式。

private void btnSubmit_Click(object sender, EventArgs e)
{
    if (lsbMathAns.SelectedItem.ToString() == txtAnswer.Text)
        MessageBox.Show("Correct answer. Well Done!", "Great Job!");
    else if
        (lsbGeoAns.SelectedItem.ToString() == txtAnswer.Text)
        MessageBox.Show("Correct answer. Well Done!", "Great Job!");


    //if (this.txtAnswer.Text.ToLower() == this.lsbGeoAns.SelectedItem.ToString().ToLower())
    //    MessageBox.Show("Correct answer. Well Done!", "Great Job!");
    //else
    //    MessageBox.Show("Sorry. Try Again...", "Wrong Answer");
    //if (this.txtAnswer.Text == this.lsbMathAns.SelectedItem.ToString())
    //    MessageBox.Show("Correct answer. Well Done!", "Great Job!");
    //else
    //    MessageBox.Show("Sorry. Try Again...", "Wrong Answer");

1 个答案:

答案 0 :(得分:-1)

这样的事情可以解决你的问题吗?

if (lsbMathAns.SelectedItem != null &&  lsbMathAns.SelectedItem.ToString() == txtAnswer.Text) ...

if (lsbMathAns.SelectedIndex >= 0 && lsbMathAns.SelectedItem.ToString() == txtAnswer.Text) ...