【发布时间】:2011-10-16 06:33:29
【问题描述】:
我看到许多对象引用未设置为对象的实例,但我在任何问题中都找不到我的场景。
我有一个名为comboBox1 的组合框。在表单加载时,我有代码来填充组合框:
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the
// 'tenderDBDataSet.tbl_Tender_To_Details' table.
// You can move, or remove it, as needed.
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT
tbl_Tender_To_Details.To_Name, tbl_Tender_To_Details.To_Address1,
tbl_Tender_To_Details.To_Address2,
tbl_Tender_To_Details.To_City, tbl_Tender_To_Details.To_PinCode "+
"FROM tbl_Tender_To_Details "+
"WHERE to_Name IS NOT NULL ", conn);
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
comboBox1.Items.Add(reader["To_Name"]);
// listBox1.Items.Add(reader[0].ToString());
// MessageBox.Show(reader[0].ToString());
}
reader.Close();
comboBox1.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(comboBox1.SelectedValue.ToString());
}
MessageBox.Show(comboBox1.SelectedValue.ToString()); 行显示:
“对象引用未设置为组合框对象的实例”。
但令我惊讶的是,索引 0 处的值设置为组合框,而表单在此对象引用消息框之后加载。
【问题讨论】:
-
在while循环后获取combobox item count,它会告诉很多信息
标签: c# winforms combobox visual-studio-2005