Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just use the Controls collection Find method:

            var aoControls = this.Controls.Find("MyControlName", true);
            if ((aoControls != null) && (aoControls.Length != 0))
            {
                Control foundControl = aoControls[0];
            }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...