1

I am trying to assign button controls text dynamically by using a loop like the following:

int ButtonNumber = 1;

while (ButtonNumber < 10)
{
    //WHAT TO DO HERE!?
    ButtonNumber++;
}

I wanna avoid the following:

button1.Text = "";
button2.Text = "";
button3.Text = "";
button4.Text = "";
button5.Text = "";
button6.Text = "";
button7.Text = "";
button8.Text = "";
button9.Text = "";

5 Answers 5

11

Ideally, don't have button1, button2 etc as variables in the first place. Have a collection (e.g. a List<Button>):

private List<Button> buttons = new List<Button>();

(EDIT: You'd need to populate this somewhere, of course...)

then to update the text later:

for (int i = 0; i < buttons.Count; i++)
{
    buttons[i].Text = "I'm button " + i;
}

This doesn't play terribly nicely with the designer, unfortunately.

You can fetch a control by ID, but personally I try not to do that. If you really want to:

for (int i = 1; i <= 10; i++)
{
    Control control = Controls["button" + i];
    control.Text = "I'm button " + i;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Don't you also need to instantiate each Button object? Also add them to the list.
Why do you NOT recommend the use of fetching the control by ID? It works like a charm!?
@Alex: You've got a collection of buttons, right? How do you deal with collections everywhere else in code? You use a collection class. Why should the UI be any different? The only difference here is the designer not really understanding the idea of a collection of controls :(
1

Create an array of buttons:

Button[] buttons = new Button[10];
for(int i = 1; i < 10; i++)
{
   buttons[i] = new Button();
   buttons[i].Text = "";
}

Comments

0

You can always use this.Controls.Find() to locate a named control in WinForms.

Comments

0

You can also do like this simply, assuming if you have all buttons in your form

foreach (Control c in this.Controls)
            {
                if (c is Button)
                {
                    c.Text = "MyButton" + (c.TabIndex + 1);
                }
            }

Comments

0

// try this

         Button btn;
         for (int n_i = 0; n_i < 10; n_i++)
            {
            btn = (Button)Controls.Find("button" + n_i,true)[0];
            btn.Text = "";
            }

Comments

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.