Find control by name in Windows Forms
]Finding controls by name in Windows forms is a convenient way to access specific elements in a form. This is especially useful when dealing with a large number of controls or automation tasks.
Solution:
To find a control by name, use the Control.ControlCollection.Find
method. This method takes a string parameter that indicates the name of the control to be searched.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
In this example, we search for a control named "textBox1" in the Controls
collection of the current form. If the control is found, it is converted to a TextBox
object and assigned to the tbx
variable.
Other usage:
Find
method can also be used in control arrays:
Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
This allows you to find multiple controls by name and perform actions on them.
Notice:
Make sure that the control name you specify is unique in the form. Otherwise, Find
may return any control with the specified name.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3