Mat*_*att 3 c# combobox beforeupdate winforms
我来自VBA世界,记得BeforeUpdate我可以在组合框上打电话.现在我在C#(并喜欢它),我想知道是否有BeforeUpdate一个ComboBox关于Winform 的呼吁?
我可以创建一个不可见的文本框并存储我需要的信息,在更新后,查看我需要的那个框,但我希望有一个更简单的解决方案.
Han*_*ant 10
WF的好处之一就是你可以轻松制作自己的东西.在项目中添加一个新类并粘贴下面的代码.编译.将新控件从工具箱顶部拖放到表单上.实现BeforeUpdate事件.
using System;
using System.ComponentModel;
using System.Windows.Forms;
public class MyComboBox : ComboBox {
public event CancelEventHandler BeforeUpdate;
public MyComboBox() {
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
private bool mBusy;
private int mPrevIndex = -1;
protected virtual void OnBeforeUpdate(CancelEventArgs cea) {
if (BeforeUpdate != null) BeforeUpdate(this, cea);
}
protected override void OnSelectedIndexChanged(EventArgs e) {
if (mBusy) return;
mBusy = true;
try {
CancelEventArgs cea = new CancelEventArgs();
OnBeforeUpdate(cea);
if (cea.Cancel) {
// Restore previous index
this.SelectedIndex = mPrevIndex;
return;
}
mPrevIndex = this.SelectedIndex;
base.OnSelectedIndexChanged(e);
}
finally {
mBusy = false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以考虑一下SelectionChangeCommited.
来自MSDN:
仅当用户更改组合框选择时才会引发SelectionChangeCommitted.不要使用SelectedIndexChanged或SelectedValueChanged来捕获用户更改,因为当选择以编程方式更改时也会引发这些事件.
当您将组合框设置为允许用户键入文本框时,这将不起作用.此外,它不会告诉您"最后"选定的项目是什么.您必须缓存此信息.但是,您无需将信息存储在文本框中.你可以使用一个字符串.