I wrote a method to handle a comboBox's SelectedIndexChanged event.
In the constructor I populated the comboBox, and this activated my event-handling method. Which I don't want since nobody clicked on the comboBox.
Is there an easy way to get the comboBox not to fire the event unless the user clicked it?
If that is not possible, is there a way to disconnect the event to the method tempo开发者_高级运维rarily? Could I just set "my_combo.SelectedIndexChanged = null" and then create a new System.EventHandler?
Or I guess I could create some kind of boolean member variable that I can switch on or off and put a branch check in my method. That seems like a kludge, though.
I have done it a lot number of times. Solution1: Delete EventHandler from designer. Populate the combobox and then set EventHandler.
Combo1.SelectedIndexChanged += new EventHandler Combo1_SelectedIndexChanged;
But it will work only if you are populating the combobox once.If you are doing it for many number of times, then you may be in a mess.
Solution2: Its my preference and I use it regularily. Change your selection change event as:
private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
if(!cb.Focused)
{
return;
}
// Here is your Code for selection change
}
So now the event will be fired only if its in focus. Hope you were looking for the same. Hope it Helps
Not sure if this is any use now but I found this answer, which seems cleaner to me.
From the MSDN Library - ComboBox.SelectionChangeCommitted Event
"SelectionChangeCommitted is raised only when the user changes the combo box selection. Do not use SelectedIndexChanged or SelectedValueChanged to capture user changes, because those events are also raised when the selection changes programmatically."
You can use both methods You proposed:
- use boolean variable
detach event method, populate combobox, attach event method like this
my_combo.SelectedIndexChanged -= my_Combo_SelectedIndexChanged; populateCombo(); my_combo.SelectedIndexChanged += my_Combo_SelectedIndexChanged;
my_Combo_SelectedIndexChanged
is the name of method you attached to the event.
I would use control.ContainsFocus instead of creating other bool. The caveat here is that you have to make sure the user has focus on that control. Either by key or mouse.
if(combo.ContainsFocus){ MyEventLogic();}
- Solution: If you're populating combobox with static values only ones, just populate them and
after
subscribe to event from code. Do not use WinForms Designer to subscribe to it. If it's not possible during loading can:
a) define a boolean variable
bool loading
, set it totrue
before you begin to populate combo with data, and in event handler checkif(loading) return;
b) Unsubsribe from event:
If subscription was:
comboBox.SelectedIndexChanged += delegate(...);
Unsubscription before you begin load data is:
comboBox.SelectedIndexChanged -= delegate(...);
As loading of data finished, subscribe again.
精彩评论