DevTips.NET

Get control by name

Om een Control te krijgen via zijn naam is het handig om dit recursief op te lossen aangezien een Form uit vele container controls (of parent controls) kan bestaan (zoals TabControls, GroupBoxes, etc.). Control.Controls bevat alleen een collectie van child controls behorend bij het huidige Control. Op designtime is er nog een snellere manier aangezien je dan rechtstreeks gebruiker kunt maken van Form.Site.Container.Components. Maar op runtime is dat niet mogelijk zodat je genoodzaakt bent om een functie als hierboven te gebruiken. De aanroep van de functie is bijvoorbeeld als volgt: (waarbij "this" de huidige Form is)

Control controlToBeFound = ControlHelper.GetControlByName(this, "NameTextBox");

 

Windows Forms

Code

public static System.Windows.Forms.Control GetControlByName(System.Windows.Forms.Control ParentControl,
    string Name)
{
    System.Windows.Forms.Control foundControl = null;
    int i = 0;
    while (foundControl == null && i < ParentControl.Controls.Count)
    {
        if (ParentControl.Controls[i].Name == Name) foundControl = ParentControl.Controls[i];
        else
        {
            if (ParentControl.Controls[i].Controls.Count > 0)
                foundControl = GetControlByName(ParentControl.Controls[i], Name); // recursive call
        } i++;
    } return foundControl;
}
comments powered by Disqus