Get control by name, including children

后端 未结 3 1962
-上瘾入骨i
-上瘾入骨i 2021-01-20 03:37

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

public Control GetControlByName(string name)
{
    Control currentControl; 

    for(int i          


        
3条回答
  •  遥遥无期
    2021-01-20 04:01

    I actually wrote some extension methods at work to do just this thing:

    public static class MyExensions ()
    {
        public static Control FindControlRecursively (this Control control, string name)
        {
            Control result = null;
    
            if (control.ID.Equals (name))
            {
                result = control;
            }
            else
            {
                foreach (var child in control.Children)
                {
                    result = child.FindControlRecursively (name);
    
                    if (result != null)
                    {
                        break;
                    }
                }
            }
    
            return result;
        }
    
        public static T FindControlRecursively (this Control control, string name)
            where T: Control
        {
            return control.FindControlRecursively (name) as T;
        }
    }
    

    Note: Null checks removed for the sake of simplicity.

    You can use it to find, say, a TextBox on your form like so:

    public class MyForm : Form
    {
        public void SetSomeText ()
        {
            var control = this.FindControlRecursively ("myTextboxName");
    
            if (control != null)
            {
                control.Text = "I found it!";
            }
    
            // Or...
    
            var control2 = this.FindControlRecursively ("myTextboxName2") as TextBox;
    
            if (control != null)
            {
                control2.Text = "I found this one, also!";
            }
        }
    }
    

    Edit

    Of course, this is a depth-first algorithm, which might be slow depending on how deep your control chain is. You might rewrite it to use a breadth-first algorithm if you see that it is too slow.

提交回复
热议问题