Friday, December 10, 2010

How to not get combobox SelectedIndexChanged be executed on load

we use combobox in our coding at the form on requirements. And its usual to call the all of the events of combobox and the time of formloading. But many of the time, we are nor interested to call those events at the time of form loading. We have tried to do so for one of my need. I have done so by a different way.

When a form arrise to the user. behind the scene, two things happen.

1. Initialize the object of the form.1
2. Constructor is called for performing all others needs.

All the events are declared at the first step of the above in the time of initialization. We can bind the data source for the combo box at the constructor calling in the 2nd step of the above.

So, when a datasource is linked to the combobox, for addaing each single value or data, each time the combo box call its event for that purpose in need. It tooks execution time.

We can exclude this only by following a simple technique. i.e


Try setting your event SelectedIndexChanged handler after setting the data source. Make sure you remove the SelectedIndexChanged event handler set by the windows form designer from your form's constructor.

This is what your code should look like:

myComboBox.DataSource = dataSource;
myComboBox.DisplayMember = "displayMember";
myComboBox.ValueMember = "valueMember";
this.myComboBox.SelectedIndexChanged += new System.EventHandler(this.myComboBox_SelectedIndexChanged);

Assuming
private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
.......................
}
already exists.