【问题标题】:Get instance of control whose event I am in获取我所在事件的控件实例
【发布时间】:2014-06-08 05:42:34
【问题描述】:

有没有办法获取我所在事件的控件实例?

    private void TextBox1_TextChanged(object sender, EventArgs e)
    {
        TextBox1.Text = "hi";
        ThisControl.Text = "hi";
    }

这样两行可以做同样的事情吗?与“This”关键字类似,但用于事件控件而不是类。

【问题讨论】:

    标签: c# visual-studio instance


    【解决方案1】:

    object sender 参数是对触发事件的控件的引用。因此,您可以按照以下方式进行操作:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
         ((TextBox)sender).Text = "hi";
    
         // Or
    
         TextBox txtBox = sender as TextBox;
         txtBox.Text = "hi";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 2022-10-21
      相关资源
      最近更新 更多