[英]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.