I have seen many object reference not set to an instance of an object questions, but I couldn't find my scenario in any.
I have a combo box named comboBox1
. While form loads I have code to populate combobox:
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());
}
The MessageBox.Show(comboBox1.SelectedValue.ToString());
line shows:
"Object reference not set to an instance of an object for combo box".
But my surprise is the value at index 0 is set to combo box while form loads after this object reference msg box.
you can try put this statement at page load and make sure the combobox has loaded with items or not??
comboBox1.SelectedIndex = 0;
if you are using winforms then try put that statement in initializecomponent() function
comboBox1.SelectedIndex = 0;