简体   繁体   中英

Access control from its event handler

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.

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";

Use the sender argument:

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

Use the sender argument:

private void label_Click(object sender, EventArgs e)
{
    Label clickedLabel = sender as Label;
    if(clickedLabel == null)
        return;
    clickedLabel.Text = "clicked"; //pseudo code
}

to slow :(

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM