2

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?

2
  • are you talking about WPF or Winforms? Commented Apr 27, 2013 at 16:26
  • It's a windows form application Commented Apr 27, 2013 at 16:28

4 Answers 4

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

this.Controls["textbox" + i] Works like a charm. Thank you!
0
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++;
}

1 Comment

You should create a List<Textbox> instead of List<string>.
0

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

Comments

0

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.

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.