【问题标题】:Eventhandler override?事件处理程序覆盖?
【发布时间】:2010-10-09 13:59:06
【问题描述】:

我试图想出一种方法来轻松检测是否对 Winform 上的控件进行了更改。这种方法有效,但它没有提供有关哪些控件已更改的信息。有没有办法覆盖 TextChanged 事件,以便它通过,而 EventArg 包含触发事件的控件的名称?当 AccountChangedHandler 执行时,sender 参数包含有关文本框的信息,例如“.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;
}

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:
    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);
    }
    

    【讨论】:

    • 啊——所以参考在发件人中!我在调试器监视窗口中查看发件人,但不太了解。您必须继续深入研究“.base”,直到您位于定义了 .Name 属性的继承基类中。
    • 如果我的帖子有帮助,您能否将其标记为答案?或者再问一个问题,我很乐意帮助你:)
    【解决方案2】:

    sender参数呢?

    【讨论】:

      【解决方案3】:

      sender 是对引发事件的控件的引用。如果你这样做了

      TextBox tb = sender as TextBox;
      string name = tb.Name;
      

      您会看到,现在您可以像使用“txtContractName”一样使用“tb”。如果你想做特定的逻辑,你可以做类似

      if(tb == txtBillAddress1) { ... }
      

      但是,此时您最好使用单独的事件处理程序。

      【讨论】:

        猜你喜欢
        • 2015-03-28
        • 2010-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-05
        • 1970-01-01
        相关资源
        最近更新 更多