user17342056
user17342056

Reputation:

In C# windows forms apps, is there a way to access buttons using integers?

I have an array, where I store the numbers of buttons, but I want to use a check function:

void check()
{
    if (counter == 2)
    {
        System.Threading.Thread.Sleep(200);
        if ((buttons[0] == 1 && buttons[1] == 6) || (buttons[0] == 6 && buttons[1] == 1))
        {
            button1.BackgroundImage = null;
            button6.BackgroundImage = null;
        }
        buttons[0] = 0;
        buttons[1] = 0;
        counter = 0;
   }
}

So I was just wondering, is there a way, to set the background image without actually declaring like this? For example like buttons[0].buttons.BackGroundImage = null; Or is there an actual way to do this?

Thanks for the answers!

Upvotes: 0

Views: 153

Answers (2)

wohlstad
wohlstad

Reputation: 28409

You can put all your Button objects in a list:

Define a member variable:

List<Button> buttonsList;

Then populate it with your actual Buttons (the objects created by the designer):

buttonsList.Add(button1);
// ...
buttonsList.Add(button6);
// ...

Now the button number will be associated with the index in the list (in this specific example there will be an offset of 1 since the first Button is button1, not button0).
So you can directly change the Button properties by doing e.g. (for the first button):

buttonsList[0].BackGroundImage = null;

Upvotes: 2

jalex
jalex

Reputation: 1524

To get an array of buttons, filter the Form.Controls property

Button[] button = this.Controls.OfType<Button>().ToArray();

then you can do things like button[0].Visibility = false; and similarly.

Upvotes: 1

Related Questions