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

Time:04-12

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!

CodePudding user response:

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 the index in the list, and you can directly change the Button properties by doing e.g. (for button #0):

buttonsList[0].BackGroundImage = null

CodePudding user response:

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.

  • Related