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;
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;
}
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;
}
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;
}
using the sender:
Try something like this:
private void label_Click(object sender, EventArg e){
((Label)sender) = ..your code
}