문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top