Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get control by name, including children

I'm trying to get a control by name. I wrote the following code:

public Control GetControlByName(string name)
{
    Control currentControl; 

    for(int i = 0,count = Controls.Count; i < count; i++)
    {
        currentControl = Controls[i];

        if (currentControl.HasChildren)
        {
            while (currentControl.HasChildren)
            {
                for(int x = 0,size = currentControl.Controls.Count; x < size; x++)
                {
                    currentControl = currentControl.Controls[x];

                    if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                    {
                        return currentControl;
                    }
                }
            }
        }
        else
        {
            if (currentControl.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                return currentControl;
            }
        }
    }

    return null;
}

It only ever returns null. Can someone point out my mistake? Any help or ways to improve this code are welcomed.

like image 900
Jack Avatar asked Dec 10 '22 03:12

Jack


1 Answers

Just use the Controls collection Find method:

            var aoControls = this.Controls.Find("MyControlName", true);
            if ((aoControls != null) && (aoControls.Length != 0))
            {
                Control foundControl = aoControls[0];
            }
like image 169
competent_tech Avatar answered Dec 25 '22 10:12

competent_tech