c# - 事件处理程序覆盖?

标签 c# .net winforms

我试图提出一种方法来轻松检测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/

相关文章:

c# - 将流转换为文件

.net - 发布没有必填字段值的新缺陷时,Rally Rest .NET API 抛出 KeyNotFoundException

.Net - 多个 ORM 的解耦工作单元模式

c# - 如何将文本框值从 Form1 复制到 Form2?

.net - 如何使用 Windows API 代码包检索存储在回收站中的项目的 'Deletion Date' 属性?

c# - 使用 System.Reflection 从 DLL 程序集中获取 DataMember

c# - 新表格问题c#

c# - 最佳实践 winforms async/await 关键字

c# - 单击按钮打开表单?

c# - 为什么在 Xamarin 中将最小 100 放在步进器类上不起作用?