简体   繁体   中英

c# - how can I handle the click event of controls created dynamically within a loop

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!

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") { /* ... */ }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM