I have a list of my textbox names, and I want to find a control by name. How is it possible?
Asked
Active
Viewed 2e+01k times
3 Answers
107
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? – krunal shah Oct 10 '10 at 01: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?) – krunal shah Oct 10 '10 at 01: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. – bla Oct 10 '10 at 01:45
-
No i am not adding dynamically.. I have already list of textboxes .. And i have stored names of all taxboxes in one array. From that array i am fetching names and than finding textboxes and than want to fetch text from the specific textbox .. – krunal shah Oct 10 '10 at 01:49
-
The extension method 'FirstOrDefault' does not exist in .net 2.0.You need to be using .net 3.5 or later for that to work. Just remove the .FirstOrDefault() and the provided code should work. – Tony Abrams Oct 10 '10 at 01:54
-
3TextBox foundTbx = this.Controls.Find(textBoxes[5], true)[0] as TextBox; – bla Oct 10 '10 at 01:56
-
1Change .FirstOrDefault() to [0] – bla Oct 10 '10 at 01:57
14
You can use:
f.Controls[name];
Where f
is your form variable. That gives you the control with name name
.

CesarGon
- 15,099
- 6
- 57
- 85
-
7Note that this doesn't work if the control is nested (you'll only find controls present at that level in the control hierarchy). – Michael Petrotta Oct 10 '10 at 01:30
-
5
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!";

Nguyen Ngoc Quyen
- 59
- 1
- 2