How to write a common ClickEvent for many labels?

2019-06-02 21:22发布

问题:

I have 10 labels on a panel - and 10 identical ClickEvents (change BackColor).
How could I reduce the code, i.e. write a common procedure ?
Something like:

foreach (Control c in panelA.Controls)
if (c.Tag == "abc" && c.is clicked)
c.BackColor = Color.Crimson;

回答1:

Iterate over labels and wire a handler to Click event:

foreach (Control c in panelA.Controls)
{
    c.Click += HandleClick;
}

Then, in the click handler, you can change the background color by using the sender parameter that will contain the label the click was made on:

private void HandleClick(object sender, EventArgs e)
{
    ((Control)sender).BackColor = Color.Crimson;
}


回答2:

Can't you wire each button to the same event handler?

button1.Click += ChangeBackColor;
button2.Click += ChangeBackColor;
...
button10.Click += ChangeBackColor;

private void ChangeBackColor(object sender, EventArgs e)
{
    Control control = (Control)sender;
    control.BackColor = Color.Crimson;
}


回答3:

You can assign each label's click event to the same event handler, and then look at the sender object in your event handler. It will tell you which label was clicked.

private void OnLabelClick(object sender, EventArgs e)
{
    var label = sender as Label;
    if(label != null)
        label.BackColor = Color.Crimson;
}


回答4:

using the sender:

Try something like this:

private void label_Click(object sender, EventArg e){
  ((Label)sender) = ..your code
}