Stoopkid
Stoopkid

Reputation: 1965

Get instance of control whose event I am in

Is there a way to get an instance of the control whose event I am in?

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

Sort of so that these two lines would do the same thing? Like the "This" keyword but for the event control rather than the class.

Upvotes: 1

Views: 99

Answers (1)

Inisheer
Inisheer

Reputation: 20794

The object sender parameter is a reference to the control that fired the event. Therefore, you could do something along the lines of:

private void textBox1_TextChanged(object sender, EventArgs e)
{
     ((TextBox)sender).Text = "hi";

     // Or

     TextBox txtBox = sender as TextBox;
     txtBox.Text = "hi";
}

Upvotes: 4

Related Questions