Reputation: 25
I want to add a event for label when a specific label is pressed, but my event handler is not reacting to the clicked label.
I created a calender so when I click a date I want to highlight that date, that's the requirement.
for (Int32 i = 1; i <= Dayz; i++)
{
ndayz += 1;
lblDayz = new Label();
lblDayz.Text = i.ToString();
lblDayz.Cursor = Cursors.Hand;
lblDayz.Name = "Date" + i;
lblDayz.Anchor = AnchorStyles.None;
lblDayz.TextAlign = ContentAlignment.MiddleCenter;
lblDayz.Click += lblDayz_Click;
}
Event handler looks like:
public void lblDayz_Click(object sender, EventArgs e)
{
lblDayz.BackColor = Color.FromArgb(176, 180, 43);
lblDayz.ForeColor = Color.White;
}
Upvotes: 2
Views: 95
Reputation: 14021
Your current implementation is trying to change the properties of lblDayz
, which might be a single label somewhere. But the way you're creating labels you have a number of labels generated in code. One for each day
That means you need your handler to react to the label that was clicked. The label that was clicked is the sender
in your event handler. Crudely then you could handle it like this
public void lblDayz_Click(object sender, EventArgs e)
{
Label clickedLabel = sender as Label;
clickedLabel.BackColor = Color.FromArgb(176, 180, 43);
clickedLabel.ForeColor = Color.White;
}
Upvotes: 2