0

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


3
  • You could use the Tag property to store the number for each button and have one event for all buttons. When the event is called you know which button was pressed based on the Tag and you can save the data in the database and also change the color. Commented Jun 11, 2020 at 19:38
  • So, you're creating 80 buttons dynamically at run-time rather than placing 80 individual buttons on the form at design time? And you want to know how to give each one of them a click event? Commented Jun 11, 2020 at 19:39
  • I'm assuming this is a Windows Form in Visual Studios, am I right? Commented Jun 11, 2020 at 19:39

1 Answer 1

2

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;
            };
        }
    }
}
Sign up to request clarification or add additional context in comments.

8 Comments

And where should i call that? Should I make that as a method and then call it to an event or how ?
Wherever you create the buttons. Add this right after creating them. Or if the buttons are created in designer, you can add this in the form constructor - after InitializeComponent();.
Yeah, the buttons are created in designer but i wasnt able to attach image in the question section.
I've updated the answer to show how to add to all buttons.
How to validate so each user should select exactly 10 buttons?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.