[英]Set ComboBox default value without directly changing SelectedIndex
我有一个带有几个项目的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时做一些事情?
删除事件处理程序(通过单击属性窗格顶部的闪电。然后清除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();
}
您可以添加属性以禁止事件执行
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.