Get control by name, including children

后端 未结 3 1959
-上瘾入骨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 03:57

    A slight tweak for if you're not using System.Windows.Forms (this is what .Find(string, bool) works off too)

    public static class MyExensions
    {
        public static Control FindControlRecursively(this Control control, string name)
        {
            Control result = null;
    
            if (control.ID.Equals(name))
            {
                result = control;
            }
            else
            {
                for (var i = 0; i < control.Controls.Count; i++)
                {
                    result = control.Controls[i].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;
        }
    }
    

    p.s. Yes I know it's an old question, but in case it helps

提交回复
热议问题