selectedindex不在组合框中工作

时间:2016-02-25 15:59:18

标签: c#

我可以知道代码的问题是什么使它不能用于selectedindex> -1

此代码正常工作

if (comboBoxSubjectCodeRegister.Text != null)
{
    OleDbCommand oda1 = new OleDbCommand("select subject_abbreviation from subjectinfo where subject_code = '" + comboBoxSubjectCodeRegister.Text + "'", con);
    textBoxSubjectAbbreviationRegister.Text = Convert.ToString(oda1.ExecuteScalar());
}

else
{
    textBox1.Text = "";
}

但这不起作用

if (comboBoxSubjectCodeRegister.SelectedIndex > -1)
{
    OleDbCommand oda1 = new OleDbCommand("select subject_abbreviation from subjectinfo where subject_code = '" + comboBoxSubjectCodeRegister.Text + "'", con);
    textBoxSubjectAbbreviationRegister.Text = Convert.ToString(oda1.ExecuteScalar());
}

else
{
    textBox1.Text = "";
}

当我使用不在另一个项目中工作的代码时,它就可以了。太奇怪了,但直到现在还不确定问题是什么

1 个答案:

答案 0 :(得分:0)

要提供“精确”的aswer,我们需要知道如何将值绑定到ComboBox。

但是,独立于此,最好在代码中使用SelectedValue属性而不是Text

if (comboBoxSubjectCodeRegister.SelectedIndex > -1)
{
    OleDbCommand oda1 = new OleDbCommand("select subject_abbreviation from subjectinfo where subject_code = '" + comboBoxSubjectCodeRegister.SelectedValue + "'", con);
    textBoxSubjectAbbreviationRegister.Text = Convert.ToString(oda1.ExecuteScalar());
}
else
{
    textBox1.Text = "";
}