Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set ComboBox default value without directly changing SelectedIndex

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?

like image 555
jacobz Avatar asked Mar 22 '23 05:03

jacobz


1 Answers

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();
}
like image 119
dovid Avatar answered Apr 25 '23 17:04

dovid