Linq is used generally to get and manipulate data by using Linq to Sql, Linq to Entities or Linq to Xml. However, it can work on many collections in .NET Framework. Now in this post, I'll show how to work on Page Control Collection with Linq. Think about the scenario you want to get every textboxes that has a text in it. To see which ones we select add them a text you want.
Create a new .aspx page and add several textboxes to it. They can be directly in page or another control (i.e. a panel control). Then add the code below to the click event of a button.
protected void Button1_Click(object sender, EventArgs e)
{
GetControls(this.Page);
//to instantiate the process
}
//this method is recursive.It starts with the control collection of
//the control given to it.
private void GetControls(Control parentControl)
{
//iterates through control collection of the parent control
//if there is textbox selects it
var controls = from c in parentControl.Controls.Cast()
let txt = c as TextBox
where (txt != null && txt.Text.Length > 0)
select c;
//add "--has text!" to each textbox
foreach (var item in controls)
{
(item as TextBox).Text += "-- has text!";
}
//recursion step: chechks whether subcontrols has
//their subcontrols and recurse on them
foreach (Control control in parentControl.Controls)
{
if (control.Controls.Count > 0)
{
GetControls(control);
}
}
}
By using the principle on the above example you can have much more control on your server (or user) controls than before with Linq.