Get All Web Controls of a Specific Type on a Page

后端 未结 8 1819
忘掉有多难
忘掉有多难 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:25

    Had this very question and while I found Steve B's answer useful, I wanted an extension method, so re-factored it:

        public static IEnumerable<T> GetControlList<T>(this ControlCollection controlCollection) where T : Control
        {
            foreach (Control control in controlCollection)
            {
                if (control is T)
                {
                    yield return (T)control;
                }
    
                if (control.HasControls())
                {
                    foreach (T childControl in control.Controls.GetControlList<T>())
                    {
                        yield return childControl;
                    }
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-01 04:27
            var dropDownLists = new List<DropDownList>();
            foreach (var control in this.Controls)
            {
                if (control is DropDownList)
                {
                    dropDownLists.Add( (DropDownList)control );
                }
            }
    
    0 讨论(0)
提交回复
热议问题