[英]Is there a BeforeUpdate for a C# ComboBox on a Winform
我来自VBA世界,记得我可以在组合框上进行一次BeforeUpdate
调用。 现在我在C#(并喜欢它),我想知道是否在BeforeUpdate
上有一个关于ComboBox
的BeforeUpdate
调用?
我可以创建一个不可见的文本框并存储我需要的信息,在更新后,查看我需要的那个框,但我希望有一个更简单的解决方案。
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;
}
}
}
您可以考虑SelectionChangeCommited
。
来自MSDN:
仅当用户更改组合框选择时才会引发SelectionChangeCommitted。 不要使用SelectedIndexChanged或SelectedValueChanged来捕获用户更改,因为当选择以编程方式更改时也会引发这些事件。
当您将组合框设置为允许用户键入文本框时,这将不起作用。 此外,它不会告诉您“最后”选定的项目是什么。 您必须缓存此信息。 但是,您无需将信息存储在文本框中。 你可以使用一个字符串。
您可以尝试ValueMemberChanged,Validating,SelectedIndexChanged或TextChanged。 它们不会像BeforeUpdate那样触发,但您可以查看将更新的内容并处理更新或拒绝更新。
开箱即用,没有那样的东西。 处理组合框中的更改的所有事件都在选择了新值之后发生。 那时,没有办法说出USED的价值。 你最好的选择就是你所能想到的。 一旦填充了ComboBox,将SelectedItem保存为临时变量。 然后,挂钩到SelectedValueChanged事件。 此时,您的临时变量将是您的旧值,SelectedItem将是您当前的值。
private object oldItem = new object();
private void button3_Click(object sender, EventArgs e)
{
DateTime date = DateTime.Now;
for (int i = 1; i <= 10; i++)
{
this.comboBox1.Items.Add(date.AddDays(i));
}
oldItem = this.comboBox1.SelectedItem;
}
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
//do what you need with the oldItem variable
if (oldItem != null)
{
MessageBox.Show(oldItem.ToString());
}
this.oldItem = this.comboBox1.SelectedItem;
}
我想你想要的是DropDown活动。 它会在用户更改之前告诉您该值是什么。 但是,用户最终可能不会更改任何内容,因此它与BeforeUpdate不完全相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.