假设有一个事件ComboBox_SelectedIndexChange就像这样
private void MyComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//do something//
}
我有一个改变ComboBox值的函数。
Private void MyFunction()
{
MyComboBox.Text = "New Value";
}
我可以让MyFunction在更改MyComboBox的值时阻止调用事件MyComboBox_SelectedIndexChanged吗?
答案 0 :(得分:2)
不,你不能。你有两个基本选择,两者都完成同样的事情:我可以让MyFunction在更改MyComboBox的值时阻止调用事件MyComboBox_SelectedIndexChanged吗?
您可以从控件中取消挂起事件处理程序方法,设置值,然后将事件处理程序方法重新附加到控件。例如:
private void MyFunction()
{
MyComboBox.SelectedIndexChanged -= MyComboBox_SelectedIndexChanged;
MyComboBox.Text = "New Value";
MyComboBox.SelectedIndexChanged += MyComboBox_SelectedIndexChanged;
}
您可以声明一个类级别字段,该字段将跟踪该值是以编程方式还是由用户更新。如果要以编程方式更新组合框,请设置该字段,并在SelectedIndexChanged
事件处理程序方法中验证其值。
例如:
private bool allowComboBoxChange = true;
private void MyComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (allowComboBoxChange)
{
//do something
}
}
private void MyFunction()
{
allowComboBoxChange = false;
MyComboBox.Text = "New Value";
allowComboBoxChange = true;
}
答案 1 :(得分:1)
您可以附加或分离事件处理程序。
//attach the handler
MyComboBox.SelectedIndexChanged+=(sender,eventArgs)=>
{
//code
};
//detach the handler
MyComboBox.SelectedIndexChanged-=(sender,eventArgs)=>
{
//code
};
或者
Private void MyFunction()
{
comboBox1.SelectedIndexChanged -= new EventHandler(TestIt);
MyComboBox.Text = "New Value";
comboBox1.SelectedIndexChanged += new EventHandler(TestIt);
}
private void TestIt(object sender, EventArgs e)
{
//do something//
}