Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access control from its event handler

Tags:

c#

winforms

I want to access a control's parameters inside it's event handler without mentioning its name.

An example makes it clear:

private void label1_Click(object sender, EventArgs e)
{
    self.text="clicked";//pseudo code
}

I want somthing like this which would change the text of label1 to "clicked" or whatever I want.

I want to do this because the software I'm making consists of large number of labels and textboxes and I prefer to just copy and paste the single code in each event handler rather than typing seperate one for each control.

Can something like this be done in C#? I am using winforms.

like image 333
Suraj Bhawal Avatar asked Feb 12 '26 19:02

Suraj Bhawal


2 Answers

The sender parameter (in pretty much all events in Windows Forms) is actually a reference to the control which fired the event.

In other words, you can simply cast it to a Control (or Label, or whatever):

private void label1_Click(object sender, EventArgs e)
{
      var ctrl = sender as Control; // or (Control)sender
      ctrl.Text = "clicked";
}

This allows you to attach the same handler method to events on multiple controls, and differentiate them using the sender parameter:

// the `label_Click` method gets called when you click on each of these controls
label1.Click += label_Click;
label2.Click += label_Click;
label3.Click += label_Click;

Another way to do this, if you want to avoid casting altogether, might be to use a lambda to capture the parent control:

label1.Click += (sender, args) => label1.Text = "Clicked";
like image 193
Groo Avatar answered Feb 15 '26 08:02

Groo


Use the sender argument:

private void label1_Click(object sender, EventArgs e)
{
    Label self = (Label)sender;
    self.text = "clicked"; //pseudo code
}
like image 42
Dmitry Avatar answered Feb 15 '26 09:02

Dmitry