Monday, August 1, 2011

Extension Method to iterate against any control on a Page

We all know that in order to iterate against any control on page a method we generally go for is
Page.FindControl.
But this is a bit tedious process when we associate the same page with Master Page which adds one more foreach loop on the top and the best vs bad part is it gives you a bit of debugging time.

I think the best way of doing this is using the Extensions method which comes with c# 3.0

public static class myExtensions
        {        
            public static IEnumerable<T> AllControls<T>(this Control ctrl) where T : Control
            {
                bool find = ctlr is T;
                if (find)
                {
                    yield return ctrl as T;
                }
                foreach (var child in ctrl.Controls.Cast<Control>())
                {
                    foreach (var item in AllControls<T>(child))
                    {
                        yield return item;
                    }
                }
            }
        }

This gives you an ease in different ways as it can used along with Lambda expressions like this
Page.AllControls<CheckBox>().Where(c => c.Checked);

or simply to iterate on the control you want to find
 var chkBox = Page.AllControls<CheckBox>();

foreach (CheckBox i in chkBox)
       {
    //Your code
       }

No comments:

Post a Comment