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