4

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.

s.k.paul
  • 7,099
  • 28
  • 93
  • 168

3 Answers3

8

If you want to perform the tasks only when user change selected item in combo box, it is better to implement the SelectionChangeCommitted event

[EDIT]

According to MSDN docs SelectionChangeCommitted occurs only when the ComboBox selection 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, SelectionChangeCommitted event is fired first and then SelectedIndexChanged event is fired.

So if we need to do anything on SelectedIndexChanged, we can remove it and do the same work in SelectionChangeCommitted event handler.

Simply handle this event instead of SelectedIndexChanged as below:

private void cmbProductName_SelectionChangeCommitted(object sender, EventArgs e)
{
    /*
      Your event handling code
    */
}
sohel khalifa
  • 5,602
  • 3
  • 34
  • 46
5

Try unregistering the event in the FormClosing event handler:

MyComboBox.SelectedIndexChanged -= combox_SelectedIndexChanged;

Laila
  • 417
  • 1
  • 3
  • 14
2

During the from closing you can remove ComboBox event handler. Therefore you need Closing event handler for your form and there you must remove cmbProductName_SelectedIndexChanged callback.

Here you can read about Form.Closing and how to remove event handler.

Community
  • 1
  • 1
besworland
  • 747
  • 2
  • 7
  • 17