How to write a common ClickEvent for many labels?

一曲冷凌霜 提交于 2019-12-08 04:22:10

问题


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
}


来源:https://stackoverflow.com/questions/11161063/how-to-write-a-common-clickevent-for-many-labels

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!