I was all excited at writing this generic function when the compiler threw an error (unable to cast T to System.Web.UI.Control
)
I basically pass it a type when I call it, and it look for all controls of that type. The error occurs on l.Add((T)ctrl);
private List<T> RecurseTypes<T>(Control ctrls)
{
var l = new List<T>();
foreach (var ctrl in ctrls.Controls)
if (ctrl.GetType() is T)
l.Add((T)ctrl);
return l;
}
Am I missing something or am I just out of luck?
private List<T> RecurseTypes<T>(Control parent) where T: Control
{
var l = new List<T>();
foreach (var child in parent.Controls)
if (child is T)
l.Add((T)child);
return l;
}
2 changes:
where T : Control
generic constraintis
usage (the control can be a T
, but GetType()
returns Type
, which is never a Control
)Also, note that this doesn't really recurse; this could just be:
return ctrl.Controls.OfType<T>().ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With