我试图提出一种方法来轻松检测Winform上的控件是否已更改。这种方法有效,但是它不提供有关已更改哪些控件的信息。有没有一种方法可以重写TextChanged事件,使其通过传递,而EventArg包含触发该事件的控件的名称?当AccountChangedHandler执行时,发件人参数包含有关文本框的信息,例如'.Text'属性的当前值,但我看不到哪个控件引发了该事件。
private bool _dataChanged = false;
internal TestUserControl()
{
InitializeComponent();
txtBillAddress1.TextChanged += new System.EventHandler(AccountChangedHandler);
txtBillAddress2.TextChanged += new System.EventHandler(AccountChangedHandler);
txtBillZip.TextChanged += new System.EventHandler(AccountChangedHandler);
txtBillState.TextChanged += new System.EventHandler(AccountChangedHandler);
txtBillCity.TextChanged += new System.EventHandler(AccountChangedHandler);
txtCountry.TextChanged += new System.EventHandler(AccountChangedHandler);
txtContactName.TextChanged += new System.EventHandler(AccountChangedHandler);
txtContactValue1.TextChanged += new System.EventHandler(AccountChangedHandler);
txtContactValue2.TextChanged += new System.EventHandler(AccountChangedHandler);
txtContactValue3.TextChanged += new System.EventHandler(AccountChangedHandler);
txtContactValue4.TextChanged += new System.EventHandler(AccountChangedHandler);
}
private void AccountChangedHandler(object sender, EventArgs e)
{
_dataChanged = true;
}
最佳答案
void AccountChangedHandler(object sender, EventArgs e)
{
string n = ((TextBox)sender).Name;
string t = ((TextBox)sender).Text;
// or instead of cast
TextBox tb = sender as TextBox; // if sender is another type, tb is null
if(tb != null)
{
string n = tb.Name;
string t = tb.Text;
}
}
你也可以尝试使用
foreach (Control c in this.Controls)
{
c.TextChanged += new EventHandler(AccountChangedHandler);
}
关于c# - 事件处理程序覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/582027/