Linq to Asp.net Archive

Linq to Asp.net controls

Be a fan

Some we use many controls on a page and we need to get their value we access them through ID and its very time consuming process, we can access through Linq , It is easy and much cleaner way. For querying on controls of page we need to create a function which can access all controls of page recursively. For this I am creating a extension method which get reference all controls recursively.


using System.Collections.Generic;
using System.Web.UI;

namespace IAnswearble.Utility
{
    public static class PageExtension
    {
        public static IEnumerable<Control> GetAllControls(this Control parent)
        {
            foreach (Control parentcontrol in parent.Controls)
            {
                yield return parentcontrol;
                foreach (Control childcontrol in parentcontrol.GetAllControls())
                {
                    yield return childcontrol;
                }
            }
        }
    }
}

Now I we can use it for any type query on controls of page, for querying we need use namespace IAnswearble.Utility

Example 1 : Get all check boxes which are selected

var selectedcheckboxes = this.GetAllControls().OfType<CheckBox>().Where(item => item.Checked);

Example 2 : Get value of all TextBoxes

using System;
using System.Linq;
using System.Web.UI.WebControls;
using IAnswearble.Utility;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            var textoftextboxes = from textbox in this.GetAllControls().OfType<TextBox>()
                                     select new { ID = textbox.ID, Text = textbox.Text };

            foreach (var textoftextbox in textoftextboxes)
            {
                Response.Write(string.Format("Value of {0} is {1}", textoftextbox.ID , textoftextbox.Text));
            }
        }
    }
}

Example 3 : Get child controls of a specific control

 var textboxofdivform = this.GetAllControls().Where(item => item.Parent.ID == DivForm.ID).OfType<TextBox>();

Be a fan