WebControls enumeration

  • Thread starter Thread starter Vik
  • Start date Start date
try something like this

foreach (Control c in this.Controls)
{
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")
{
// ...do something...
}
}



--
Regards

John Timney (Microsoft ASP.NET MVP)
----------------------------------------------
<shameless_author_plug>
Professional .NET for Java Developers with C#
ISBN:1-861007-91-4
Professional Windows Forms
ISBN: 1861005547
Professional JSP 2nd Edition
ISBN: 1861004958
Professional JSP
ISBN: 1861003625
Beginning JSP Web Development
ISBN: 1861002092
</shameless_author_plug>
 
If you're using VB try this:

For Each (Control c in Controls)
if TypeOf c is System.Web.UI.WebControl Then
// ...do something...
Next

-Mark
 
actually you need to recurse, or you will miss controls in usercontrols,
grids, etc.

walkControls(this.Controls);

void walkControls (Control c)
{
foreach (Control child in this.Controls)
{
walkControl(child);

if
(child.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox")
{
// ...do something...
}
}
}
}
 
Thanks everybody.
Originally I had code like this which worked fine:

CtlType = ctl.GetType.Name
Select Case CtlType
Case "TextBox"
....
Case "Label"
....
End Select

I changed it to:
If TypeOf ctl Is TextBox Then
....
ElseIf TypeOf ctl Is Label Then
....
End If

This code does not work because TypeOf ctl Is Label = True for example when
CtlType="CompareValidator".

Vik
 
Back
Top