Reputation: 3291
I got a ComboBox with a couple of items. I want to put SelectedIndex
of the ComboBox to 0
, so when the user starts it, the first item is already selected (as default).
However, doing this (combobox.SelectedIndex = 0;
) interferes with my event combobox_SelectedIndexChanged()
, which occurs when the user changes the SelectedIndex of the ComboBox, restarting the program:
private void combobox_SelectedIndexChanged(object sender, EventArgs e)
{
Process.Start(Application.ExecutablePath);
this.Close();
}
This will cause combobox_SelectedIndexChanged()
to loop endlessy, ascombobox.SelectedIndex = 0;
will trigger it, which again will trigger the other one and so forth...
Is there any way to let the program do something upon changing of the SelectedIndex by the user without this looping?
Upvotes: 4
Views: 23722
Reputation: 6491
remove the event handler (by click the lightning bolt at the top of the properties pane. then clear the SelectedIndexChanged handler).
and in constructor code, first set the SelectedValue, and then add the event handler. here:
public Form1()
{
InitializeComponent();
comboBox1.SelectedIndex = 0;
comboBox1.SelectedIndexChanged += combobox_SelectedIndexChanged;
}
private void combobox_SelectedIndexChanged(object sender, EventArgs e)
{
Process.Start(Application.ExecutablePath);
this.Close();
}
Upvotes: 7
Reputation: 904
You can add a property to suppress event execution
internal bool SupressSelectIndexChanged {get; set;}
private void SomeCallingMethod(){
this.SupressSelectIndexChanged = true;
combobox.SelectedIndex = 0;
this.SupressSelectionIndexChanged = false;
}
private void combobox_SelectIndexChanged(object sender, EventArgs e){
if(this.SupressSelectIndexChanged){ return; }
// - execution logic
}
Upvotes: 0