Get All Web Controls of a Specific Type on a Page

后端 未结 8 1857
忘掉有多难
忘掉有多难 2020-12-01 03:58

I have been pondering how I can get all controls on a page and then perform a task on them in this related question:

How to Search Through a C# DropDownList Programm

8条回答
  •  暖寄归人
    2020-12-01 04:09

    Here is a recursive version that returns a control collection of the requested type instead of utilizing another argument:

    using System.Collections.Generic;
    using System.Web.UI;
    // ...
    public static List GetControls(ControlCollection Controls)
    where T : Control {
      List results = new List();
      foreach (Control c in Controls) {
        if (c is T) results.Add((T)c);
        if (c.HasControls()) results.AddRange(GetControls(c.Controls));
      }
      return results;
    }
    

    Insert into your class (static optional).

提交回复
热议问题