Senki Sem
Senki Sem

Reputation: 131

Handling variables dynamically in C#

Let's say I've 5 texboxes:

 textbox1
 textbox2
 textbox3
 textbox4
 textbox5

I want to write something in each. Is there a way to do that with a loop? I am thinking about something that looks like:

for (int i = 1; i < 6; i++)
{
    textbox[i].Text = i.ToString();   
}

So I'd get a number in each textbox. Or is there a way of having an array of textboxes?

Upvotes: 2

Views: 151

Answers (4)

Rao Ehsan
Rao Ehsan

Reputation: 778

Create an array of Text Boxes of required size and textbox refernces to it. in your case.

TextBox[] textBoxes = new TextBox[5];
textboxes[0] = textbox1;
textboxes[1] = textbox2;
textboxes[2] = textbox3;
textboxes[3] = textbox4;
textboxes[4] = textbox5;

for (int i = 1; i < 6; i++)
{
    textbox[i].Text = i.ToString();
}

Hope this will help.

Upvotes: 0

Martin Mulder
Martin Mulder

Reputation: 12944

Verious options:

  • If your controls are in the same container (like in the same panel): use this.Controls.OfType<TextBox> as csharpler said.
  • If your controls are in various containers (like in a table inside in rows) you could choose for two options:

The static option:

Create a static array:

TextBox[] textboxes = new[] { textbox1, textbox2, textbox3, textbox4, ... };
for (int i=0; i < textBoxes.Length; i++)
    textboxes[i].text = (i + 1).toString();   

The dynamic option:

static public SetTextBoxIndex(ControlCollection controls, ref int index)
{
    foreach(Control c in controls)
    {
        TextBox textbox = c as TextBox;
        if (textbox != null)
            textbox.Text =(++index).ToString();
        else
            SetTextBoxIndex(c.Controls, ref index);
    }
}

// Somewhere on your form:
int index = 0;
SetTextBoxIndex(this.Controls, ref index);

Upvotes: 0

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98740

List<Textbox> list = new List<Textbox>() {textbox1, textbox2, textbox3, textbox4, textbox5};
int i = 1;
foreach (var item in list)
{
        item.Text = i.ToString();
        i++;
}

If these 5 textboxes is your all textboxes in this form, you can use also;

int i = 1;
foreach(var item in this.Controls.OfType<TextBox>())
{
       item.Text = i.ToString();
       i++;
}

Upvotes: 0

pascalhein
pascalhein

Reputation: 5846

Consider using this.Controls.OfType<TextBox>, which will give you a list with all the TextBoxes on your form.

You could also access them by name with this.Controls["textbox" + i]. (http://msdn.microsoft.com/en-us/library/s1865435.aspx)

Upvotes: 4

Related Questions