-1

I am wondering is there a way of shortening my code by creating a concatenation for the name of my buttons. I have tried a few things but didn't work. I have 10 buttons and named all btnCab1, btnCab2 etc and I want to add them to a list of buttons without using btn.Add(btnCab1) for every single one of them. This is the example:

 List<Button> btn = new List<Button>();
            btn.Add(btnCab1);
            btn.Add(btnCab2);
            btn.Add(btnCab3);
            btn.Add(btnCab4);
            btn.Add(btnCab5);
            btn.Add(btnCab6);
            btn.Add(btnCab7);
            btn.Add(btnCab8);
            btn.Add(btnCab9);
            btn.Add(btnCab10);
            foreach (CheckingIn c in inCabin)
            {
                int val = c.CabinNumber;
                foreach(Button b in btn)
                {
                    if(val == (btn.IndexOf(b) + 1))
                    {
                        b.BackColor = Color.Red;
                    }
                }
             }

However, let's also take into consideration that I may have 100 buttons. Thank you in advance!

danH
  • 105
  • 10
  • 3
    `List – Flydog57 Mar 12 '21 at 23:33
  • == "object references" or *object variables* – Ňɏssa Pøngjǣrdenlarp Mar 12 '21 at 23:39
  • Thanks for your time Flydog, what happens if I will have 120 buttons? I looking more for a loop possibility rather than manually entering it. – danH Mar 12 '21 at 23:41
  • 1
    That's not what your question asked. – LarsTech Mar 12 '21 at 23:41
  • 2
    We're just trying to help get your question right. Depending on what you are actually trying to do determines what the correct answer is. – LarsTech Mar 13 '21 at 00:11

1 Answers1

1

The Controls property of the form or the common parent control of the buttons will give you a collection of all the controls existing there. You can use the string indexer to access one of the controls by name.

List<Button> btn = new List<Button>();

// From 1 to 120
for(int i=1; i<= 120; i++)
{
    // Construct button name
    string buttonName = "btnCab" + i;

    // Try to find button with that name
    Button button = Controls[buttonName] as Button;

    // If found, add to list
    if (button != null)
    {
        btn.Add(button);
    }
}

I'd like to add that this is not a very good programming style.

You aren't going to add these 100 buttons at design time. When adding the buttons from code, you can place them in a list at that time and then use that list later on to access them. If you want to create a mapping between a number and a button, use a Dictionary instead of a list, for example.

NineBerry
  • 26,306
  • 3
  • 62
  • 93