Birdman
Birdman

Reputation: 5414

Assign button text dynamically via a loop

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 = "";

Upvotes: 1

Views: 5414

Answers (5)

Jerry Chiang
Jerry Chiang

Reputation: 1

// 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 = "";
            }

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500095

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

Upvotes: 11

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

Upvotes: 0

Richard Harrison
Richard Harrison

Reputation: 19393

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

Upvotes: 0

Tudor
Tudor

Reputation: 62439

Create an array of buttons:

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

Upvotes: 1

Related Questions