I am creating a custom control that inherits from ComboBox. I need to detect when a Item is added to the ComboBox to perform my own checks. It doesn\'t matter if it\'s C# or Vb.
I was recently struggling with the same question and found the documentation and other web posts lacking. At its heart a Windows Forms ComboBox is two controls in one. A compact ListBox and a TextBox. I wanted to detect when a user had typed a new entry into the TextBox that wasn't contained in the Items collection so that the new item could be processed and possibly added to the list of items to be selected.
The control doesn't define an event covering this case directly and the TextChanged event is far too granular.
What I found was the following logic in a Leave event handler to detect a potential new item that isn't on the list.
void cb_Leave(object sender, EventArgs e) {
if (cb.SelectedIndex < 0 && string.IsNullOrEmpty(cb.Text)) {
// The Text represents the potential new item provided by the user
// Insert validation, value generation, etc. here
// If the proposed text becomes a new item, add it to the list
ListItemType newItem = new ListItemType(cb.Text);
cb.Items.Add(newItem);
// And don't forget to select the new item so that the
// SelectedIndex and SelectedItem are updated to reflect the addition
cb.SelectedItem = newItem;
}
}
If you are simply using string values as your list item, then the newItem above is simply the cb.Text.