代码之家  ›  专栏  ›  技术社区  ›  Joe

事件处理程序覆盖?

  •  0
  • Joe  · 技术社区  · 17 年前

    我正试图想出一种方法来轻松检测winform上的控件是否发生了更改。这种方法是有效的,但它不提供有关哪些控件已更改的信息。是否有方法重写TextChanged事件,使其传递包含触发事件的控件名称的EventArg?当AccountChangedHandler执行时,sender参数包含有关textbox的信息,例如“.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;
    }
    
    3 回复  |  直到 17 年前
        1
  •  6
  •   abatishchev Karl Johan    17 年前
    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);
    }
    
        2
  •  2
  •   Gerrie Schenck    17 年前

        3
  •  2
  •   Jeff Moser    17 年前

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

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

    您将看到,现在您可以像使用“txtContractName”一样使用“tb”

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

    推荐文章