设置ComboBox默认值而不直接更改SelectedIndex

时间:2013-12-23 17:55:11

标签: c# winforms combobox selectedindexchanged

我有一个带有几个项目的ComboBox。我想将ComboBox的SelectedIndex放到0,所以当用户启动它时,第一个项目已被选中(默认情况下)。

但是,执行此操作(combobox.SelectedIndex = 0;)会干扰我的事件combobox_SelectedIndexChanged(),当用户更改ComboBox的SelectedIndex时,会发生该事件,重新启动程序:

private void combobox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Process.Start(Application.ExecutablePath);
            this.Close();
        }

这将导致combobox_SelectedIndexChanged()无休止地循环,因为combobox.SelectedIndex = 0;将触发它,这将再触发另一个等等......

有没有办法让程序在没有循环的情况下由用户更改SelectedIndex时做某事?

2 个答案:

答案 0 :(得分:7)

删除事件处理程序(通过单击属性窗格顶部的闪电。然后清除SelectedIndexChanged处理程序。)

并在构造函数代码中,首先设置SelectedValue,然后添加事件处理程序。 这里:

public Form1()
{
    InitializeComponent();

    comboBox1.SelectedIndex = 0;
    comboBox1.SelectedIndexChanged += combobox_SelectedIndexChanged;
}

private void combobox_SelectedIndexChanged(object sender, EventArgs e)
{
    Process.Start(Application.ExecutablePath);
    this.Close();
}

答案 1 :(得分:0)

您可以添加属性以禁止事件执行

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
}