Find a control in Windows Forms by name
TextBox txtAmnt = (TextBox)this.Controls.Find("txtAmnt" + (i + 1), false).FirstOrDefault();
This works when you know what you are loking for.
You can use the form's Controls.Find() method to retrieve a reference back:
var matches = this.Controls.Find("button2", true);
Beware that this returns an array, the Name property of a control can be ambiguous, there is no mechanism that ensures that a control has a unique name. You'll have to enforce that yourself.
If you are in a user control and don't have direct access to container form you can do the following
var parent = this.FindForm(); // returns the object of the form containing the current usercontrol.
var findButton = parent.Controls.Find("button1",true).FirstOrDefault();
if(findButton!=null)
{
findButton.Enabled =true; // or whichever property you want to change.
}
The .NET Compact Framework does not support Control.ControlCollection.Find.
See Control.ControlCollection Methods and note that there is no little phone icon beside the Find method.
In that case, define the following method:
// Return all controls by name
// that are descendents of a specified control.
List<T> GetControlByName<T>(
Control controlToSearch, string nameOfControlsToFind, bool searchDescendants)
where T : class
{
List<T> result;
result = new List<T>();
foreach (Control c in controlToSearch.Controls)
{
if (c.Name == nameOfControlsToFind && c.GetType() == typeof(T))
{
result.Add(c as T);
}
if (searchDescendants)
{
result.AddRange(GetControlByName<T>(c, nameOfControlsToFind, true));
}
}
return result;
}
Then use it like this:
// find all TextBox controls
// that have the name txtMyTextBox
// and that are descendents of the current form (this)
List<TextBox> targetTextBoxes =
GetControlByName<TextBox>(this, "txtMyTextBox", true);