I am using Combobox SelectedIndexChanged event to perform few tasks. It is working nice. But when i am closing the form, SelectedIndexChanged gets fired and i get “Object reference not set to an instance of an object.” exception. My code is following-
private void cmbProductName_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
Product p =(Product) cmbProductName.SelectedItem;
RawItems = RawItem.GetEntityList(p.Id, ConnectionString);
}
catch (Exception ex)
{
CustomMessageBox.ShowSystemException(ex);
}
}
How to avoid the SelectedIndexChanged event being fired when form is closing?
Thanks
SKPaul.
If you want to perform the tasks only when user change selected item in combo box, it is better to implement the
SelectionChangeCommittedevent[EDIT]
According to MSDN docs
SelectionChangeCommittedoccurs only when theComboBoxselection changes by user (via keyboard or mouse) and it is not raised when the selection changes programmatically.When a value is changed in the list,
SelectionChangeCommittedevent is fired first and thenSelectedIndexChangedevent is fired.So if we need to do anything on
SelectedIndexChanged, we can remove it and do the same work inSelectionChangeCommittedevent handler.Simply handle this event instead of
SelectedIndexChangedas below: