Dropdownlist checks if index has changed by code or by choice

I have a DropDownList in a project. This DropDownList contains the SelectedIndexChanged event:

 private void cbo_SelectedIndexChanged(object sender, EventArgs e){......} 

Is it possible to check if the index has been changed in the code, for example:

 cbo.SelectedIndex = placering; 

or if the change occurred while interacting with the user?

+6
source share
2 answers

Since DropDownList does not have the Focused property, as well as for controlling ComboBox in WinForms , it is not so simple. One way is to add a custom flag and change its value before changing the SelectedIndex property. Inside the event handler, you can check this flag and reset its value:

 private volatile bool isAutoFired = false; 

Then somewhere in the code:

 isAutoFired = true; cbo.SelectedIndex = placering; private void cbo_SelectedIndexChanged(object sender, EventArgs e) { if(!isAutoFired) { // event is fired by user } isAutoFired = false; } 
+5
source

You can remove the event handler in the code on the right before programming the selection change, and then add it back immediately. This is my favorite approach. No flags needed.

 cbo.SelectedIndexChanged -= cbo_SelectedIndexChanged; cbo.SelectedIndex = 1 // or what you do to change the index cbo.SelectedIndexCHanged += new EventHandler(cbo_SelectedIndexChanged); 
+1
source

All Articles