Linq to Asp.net controls

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>();

5 thoughts on “Linq to Asp.net controls

  1. Pingback: My Homepage
  2. Wow, incredible blog format! How lengthy have you been blogging for? you make running a blog glance easy. The full glance of your site is fantastic, as smartly the content material! 213707

    1. Hi,

      Another way to do the same thing(easier IMHO) would be to just use a few chaining methods and a lambda expression

      // Loop through the form TextBoxes and enable or disable each one
      this.Controls
      .OfType()
      .ToList()
      .ForEach(t => t.Enabled = true);

Leave a Reply

Your email address will not be published. Required fields are marked *