Set ComboBox default value without directly changing SelectedIndex

jacobz picture jacobz · Dec 23, 2013 · Viewed 22.1k times · Source

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?

Answer

dovid picture dovid · Dec 23, 2013

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();
}