I have a list of my textbox names, and I want to find a control by name. How is it possible?
3 Answers
Use Control.ControlCollection.Find.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
EDIT for asker:
Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
tbxs[0].Text = "Found!";
}
-
TextBox tBox = this.Controls.Find(txtbox_and_message[0, 0], true).FirstOrDefault() as TextBox; Is it OK? Oct 10, 2010 at 1:37
-
Getting this error.. .net framework 2.0.. 'System.Array' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?) Oct 10, 2010 at 1:43
-
Are you dynamically adding textbox into your form during runtime? If this is the case, you can assign a unique name to each textbox, and use controls.find to find the textbox with its unique name.– blaOct 10, 2010 at 1:45
-
3
-
1
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.
-
7Note that this doesn't work if the control is nested (you'll only find controls present at that level in the control hierarchy). Oct 10, 2010 at 1:30
-
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
If Controls.Find is not found "textBox1" => error. You must add code.
If(tbx != null)
Edit:
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
tbx.Text = "found!";