简体   繁体   中英

How to attach Click event dynamically to multiple buttons?

I'm trying to develop Keno Game in C#, so I have 80 buttons where each of them has the numbers from 1-80 like this:

基诺游戏

So what I want to do is that each user should choose 10 numbers (not less, not more) and when a button is being clicked the background color of the button turns green, but I want to know how can that be done without calling the event on each button. These numbers should be saved on the database.

I have tried adding the buttons on a array and looping through the array like this:

var buttons = new[] { button1, button2, button3, button4, button5, ..... };
foreach (var button in buttons)
{
    if (button.Focused)
    {
        button.BackColor = Color.Green;
    }
}


You can assign the same event handler to each button:

foreach (var button in buttons) {
    button.Click += (sender, e) => {  
        ((Button)sender).BackColor = Color.Green;
    };
}

If you want to add to all buttons on the form, you can call this in the form constructor:

int counter = 0;
public Form1()
{
    InitializeComponent();
    foreach (var c in Controls)
    {
        if (c is Button)
        {
            ((Button)c).Click += (sender, e) =>
            {
                if (counter >= 10) return;
                Button b = (Button)sender;
                b.BackColor = Color.Green;
                counter += 1;
            };
        }
    }
}

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