Reputation: 63
I have 100 textBoxes
, I want to set a value to all of them using a for loop.
for(int i=0; i<100; i++)
{
textBox1.AppendText("a");
}
but the textBox
ID has to change dynamically like textBox1
,textBox2
,textBox3
etc...
How can I do this?
Upvotes: 2
Views: 461
Reputation: 37337
Try this code:
for (int i = 1; i <= numberOfTextBoxes; i++)
{
var tb = this.Controls.Find("textBox" + i, true).FirstOrDefault();
if(tb != null)
tb.Text = "hello " + i;
}
Upvotes: 1
Reputation: 4104
Put all the TextBoxes in a list.
Or put them in a control and then query them. Call this method with typeof TextBox.
public IEnumerable<Control> GetAll(Control control,Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl,type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
EDIT: As mentioned in the comments, you can also pas the Form to this method. Or query the controls directy from the form.
Upvotes: 0