0

I'm looking for some advice on how to add click event handlers to labels that have been created created dynamically within a loop.

I've searched for click event handlers on dynamically created controls but this always comes back with single controls that aren't within an array.

example of code:

                //create an array of 16 labels
                Label[] label = new Label[16];

                //loop through the array of labels
                for (int i = 0; i < label.Length; i++)
                {
                    label[i]        = new Label();              //create new label
                    label[i].Name   = "lbl" + i.ToString();     //give the label a name
                    label[i].Text   = "label " + i.ToString();  //give the label text
                } 

Any help and advice on this would be great, thanks!

Paul Alexander
  • 2,686
  • 4
  • 33
  • 69
  • [Dynamic Button Creation - How to create a magic square using Windows Forms?](http://stackoverflow.com/a/33969228/3110834) – Reza Aghaei Feb 16 '17 at 16:12

1 Answers1

3

Add a handler:

label[i].Click += HandleLabelClick;

void HandleLabelClick(object sender, EventArgs e)
{
    // ...
}

Note that you can determine which label was clicked by using the sender argument:

void HandleLabelClick(object sender, EventArgs e)
{
    var label = (Label) sender;
    if (label.Text == "this or that") { /* ... */ }
}
rory.ap
  • 34,009
  • 10
  • 83
  • 174