How to Access Controls using ASP.NET Controls Collection

Waqas Anwar
29 November 2010
4814 Views

ASP.NET Page and other Container controls have a Controls collection property which you can loop through to access all or any particular type of control.

protected void Button1_Click(object sender, EventArgs e)
{
   string text = "";
   foreach (Control topLevelControl in Page.Controls)
   {
      foreach (Control childControl in topLevelControl.Controls)
      {
         if (childControl is TextBox)
         {
            text += ((TextBox)childControl).Text + ",";
         }
      }            
   }

   Label1.Text = text.Substring(0, text.Length - 1);
}