WinForms ComboBox does not always fire SelectionChangeCommitted

Today I ran into the problem that a ComboBox in my project did not always fire the SelectionChangeCommitted event when I expected it to. To be specific, if a user dropped down the list, used the arrow keys to move to an item, and then TABbed to the next control, the new item would be selected but the event never fired. This was a problem for me, because I relied on this event to filter the items in the next control, depending on the selection made in the first.

Some googling quickly learned that this was a known problem with the ComboBox, although the thread is about the SelectedIndexChanged event, it appears the same error prevents SelectionChangeCommitted from behaving as expected. As user comecme in that thread pointed out, there even was a knowledgebase item including a workaround available from Microsoft. But as he also points out… the workaround does not work.

So I decided to cook up my own solution. This would involve subclassing the Combobox to change the behavior I needed. I had one advantage, I was already using a subclassed ComboBox in all places I needed this behavior, so no Find+Replace was required to replace all standard ComboBoxes with my own.

To this subclassed combobox (named CatalogComboBox) I added the following code:

private CatalogComboItem keepSelection;

protected override void OnEnter(EventArgs e) {
  keepSelection = this.SelectedItem;
  base.OnEnter(e);
}

protected override void OnLeave(EventArgs e) {
  if (this.SelectedItem != keepSelection)
    OnSelectionChangeCommitted(EventArgs.Empty);
  base.OnLeave(e);
}

protected override void OnSelectionChangeCommitted(EventArgs e) {
  base.OnSelectionChangeCommitted(e);
  keepSelection = this.SelectedItem;
}

(I used CatalogComboItem because my combo items where typed as such, but you can always use object.) It’s a not spectacularly elegant or high-tech solution, but it works like a charm.

Advertenties

Over Shiftkey
I am Maarten, owner of and chief software developer for Shiftkey software development from The Netherlands. I will be writing mainly about things I run into when programming in C# or Delphi.

Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen.

WordPress.com logo

Je reageert onder je WordPress.com account. Log uit / Bijwerken )

Twitter-afbeelding

Je reageert onder je Twitter account. Log uit / Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit / Bijwerken )

Google+ photo

Je reageert onder je Google+ account. Log uit / Bijwerken )

Verbinden met %s

%d bloggers liken dit: