How to find all instances of a particular control type in asp.net page
By Peter Bromberg
Generically walking the control tree and returning a List<TextBox> for example.
Usage:
protected void Button1_Click(object sender, EventArgs e)
{
List<TextBox> list= Util.FindControl<TextBox>(this.Controls);
foreach (var t in list)
this.divStuff.InnerText += t.ID + ": ";
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Findcontrols
{
public class Util
{
public static List<T> FindControl<T>(System.Web.UI.ControlCollection Controls) where T : class
{
List<T> list = new List<T>();
T
found = default(T);
if (Controls != null && Controls.Count > 0)
{
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is T)
{
found
= Controls[i] as T;
list.Add(found);
break;
}
else
{
var k= FindControl<T>(Controls[i].Controls);
list.AddRange(k);
}
}
}
return list;
}
}
}
How to find all instances of a particular control type in asp.net page (469 Views)