Better way to find control in ASP.NET

后端 未结 9 1385
太阳男子
太阳男子 2020-11-22 03:17

I have a complex asp.net form,having even 50 to 60 fields in one form like there is Multiview, inside MultiView I have a GridView, and inside GridV

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:04

    All the highlighted solutions are using recursion (which is performance costly). Here is cleaner way without recursion:

    public T GetControlByType(Control root, Func predicate = null) where T : Control 
    {
        if (root == null) {
            throw new ArgumentNullException("root");
        }
    
        var stack = new Stack(new Control[] { root });
    
        while (stack.Count > 0) {
            var control = stack.Pop();
            T match = control as T;
    
            if (match != null && (predicate == null || predicate(match))) {
                return match;
            }
    
            foreach (Control childControl in control.Controls) {
               stack.Push(childControl);
            }
        }
    
        return default(T);
    }
    

提交回复
热议问题