Egzon Murati
Egzon Murati

Reputation: 3

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:

KenoGame

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;
    }
}


Upvotes: 0

Views: 1158

Answers (1)

001
001

Reputation: 13533

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;
            };
        }
    }
}

Upvotes: 2

Related Questions