简体   繁体   中英

How do I add a click event to individual dynamically generated objects?

This code I am writing right now generates a variable amount of independent objects. Can I give each of those objects the property that if it it clicked, that single object changes color?

Here is an example using a button.

var button = new Button();
//set other properties...
button.Click += Button_Click; //the event already exists

Now cast the sender (the control that was clicked) and change the back color

private void Button_Click(object sender, EventArgs e)
{
    var theButton = (Button)sender;
    theButton.BackColor = Color.Red;
}

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