user8785416
user8785416

Reputation:

Setting a event to an object in an array c#

(Wording might be terrible in the title)

I have an array of labels, I want to add mouse enter, and leave events on those labels.

This labels are created programmatically:

            Label [] lblData = new Label[255];
        int calcLoc = 0;
        for (int i = 0; i <= 200; i++)
        {
            calcLoc = 25 * i;
            lblData[i] = new Label();
            lblData[i].Location = new Point(10, calcLoc);
            lblData[i].Text = "Test " + i;
            InfoPanel.Controls.Add(lblData[i]);

        }

What I've tried: Setting the event in the loop (obviously wasn't going to work)

lblData[i].MouseEnter += (sender, e) => {lblData[i].BackColor = Color.LightBlue;};

Setting the event before the loop (figured this might have a chance)

lblData[].MouseEnter += (sender, e) => {lblData[].BackColor = Color.LightBlue;};

Neither work.

Upvotes: 0

Views: 301

Answers (2)

Zer0
Zer0

Reputation: 7354

You can use a single method and the sender parameter. Here's code with minimal changes. You could have a standalone static method instead for all events and just check sender.

lblData[i].MouseEnter += (sender, e) => {((Label)sender).BackColor = Color.LightBlue;};

Safer, and slightly faster version, that all Label instances can subscribe to below.

Static methods are better for performance for reasons I won't go into, you avoid using closures, and this ensures the event was fired by a Label.

private static void label_MouseEnter(object sender, EventArgs e)
{
   var label = sender as Label;
   if (label == null)
      return;
   label.BackColor = Color.LightBlue;
}

Upvotes: 2

Enigmativity
Enigmativity

Reputation: 117064

How about this?

Label[] lblData = new Label[255];
int calcLoc = 0;
for (int i = 0; i <= 200; i++)
{
    calcLoc = 25 * i;
    Label label = new Label();
    label.Location = new Point(10, calcLoc);
    label.Text = "Test " + i;
    label.MouseEnter += (sender, e) =>
    {
        label.BackColor = Color.LightBlue;
    };
    InfoPanel.Controls.Add(label);
    lblData[i] = label;
}

Or even this:

Label[] lblData =
    Enumerable
        .Range(0, 201)
        .Select(i =>
        {
            var calcLoc = 25 * i;
            Label label = new Label();
            label.Location = new Point(10, calcLoc);
            label.Text = "Test " + i;
            label.MouseEnter += (sender, e) =>
            {
                label.BackColor = Color.LightBlue;
            };
            InfoPanel.Controls.Add(label);
            return label;
        })
        .ToArray();

Upvotes: 3

Related Questions