Find controls by name in Windows Forms
In Windows Forms, it is often necessary to programmatically access specific controls on the form, especially if you have many controls and need to interact with them dynamically. One of the most straightforward ways is to search for them using their name.
Use Control.ControlCollection.Find
The Control class provides a Find method in its ControlCollection property. This method allows you to search for a control by name, returning the first matching control, or null if no control with that name is found.
For example, if you have a textbox called "textBox1" and you want to access it programmatically:
<code class="language-c#">TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox; tbx.Text = "找到!";</code>
This code snippet will assign the text box to the "tbx" variable and update the text content to "Found!"
Instructions for the questioner
In your specific case, you have an array of textbox names in a 2D array, where each row contains two elements: the textbox name and a message. You can adapt the above method to find and access each textbox using its name:
<code class="language-c#">Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true); if (tbxs != null && tbxs.Length > 0) { tbxs[0].Text = "找到!"; }</code>
By leveraging the Control.ControlCollection.Find method, you can efficiently locate and interact with controls on Windows Forms regardless of their position or visibility.
The above is the detailed content of How Can I Programmatically Locate and Access Windows Forms Controls by Name?. For more information, please follow other related articles on the PHP Chinese website!