There is a possibility when you have handled SelectedIndexChanged or SelectedValueChanged or any other event. That will be called when you set the DataSource property of your combobox.
This happens because ValueMember is not set when DataSource is being assigned. Suppose you have written a line of code in the SelectedValueChanged event of your combobox like this.
String myVal = dropdownCourses.SelectedValue.ToString();
Here, I am trying to convert SelectedValue into string type value.
This code will get executed immediately after assigning DataSource of Combobox and before assigning ValueMember property. So, that means the combobox doesn't have the ValueMember field.
So, the value in SelectedValue property will be null and null cannot have any property or method where we are trying to convert it into string. So, this will throw the error object reference of instance of an object is not set.
Solution:
You should set the ValueMember and DisplayMember properties before assigning DataSource to the ComboBox.
dropdownCourses.ValueMember = "ID"; //First
dropdownCourses.DisplayMember = "Course"; //Second
dropdownCourses.DataSource = dt.Tables[0]; //Third
The second way is that you can create a boolean flag to avoid the unnecessary event call during the populating combobox.
bool bLoading = false;
{
dt = db.getCourses(depID, academicYearValue, semID);
if (dt.Tables[0].Rows.Count > 0)
{
bLoading = true;
try
{
dropdownCourses.DataSource = dt.Tables[0];
dropdownCourses.DisplayMember = "Course";
dropdownCourses.ValueMember = "ID";
}
catch{}
finally{
bLoading = false; //make sure that this variable must be false after populating combobox otherwise event will not work
}
}
}
private void dropdownCourses_SelectedValueChanged(....)
{
if (!bLoading)
{
Write your code here.
}
}
I would like to suggest second option if you don't want to call event unnecessarily.