Looping
Through Controls in ASP.NET
One of the most frequently asked question in newsgroups is "How to loop
through controls in ASP.NET". Most common answer for this question
is "Use the controls Property of Page Class". This controls
property gives collection of subcontrols for that control. But if the
subcontrol is having any child controls, then it is difficult to get that
controls using this property alone. For that we need to write some recursive
function to get all the controls in a ASP.NET Page. In this article, we are
going to see how we can loop through all the controls in a web page.
Consider
we have five textbox in a web page, we need to loop through these controls and
display its name and value in a datagrid. Before we proceed to know how we can
loop through these controls. We need to create utility class which stores name
and value of a textbox. This utility class is like this,
Public Class UtilityObj
Private _name As String
Private _value As String
Public Sub New(ByVal Name As String, ByVal Value As String)
_name = Name
_value = Value
End Sub
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Name
End Set
End Property
Public Property Value() As String
Get
Return (_value)
End Get
Set(ByVal Value As String)
_value = Value
End Set
End Property
End Class
Basically
this utility class has two property namely "name" and "value" which holds the
name and value of the textbox. We have one public arraylist(oArraylist) in this
page which holds list of this utilityclass which can be binded to the datagrid.
This Page which has five textbox and one datagrid will look this,
For
looping through controls in a page, we need to write one generic function. This
function accepts a control as its parameter, then if this control is textbox.
Then it will store its name and value in utilityclass and add this object to
that arraylist. Then it will check if this control has subcontrol, if it is
there then it will call the same function for its subcontrols. Like this it
will loop through all the controls in a page. This generic function is shown
below,
Public Sub LoopingControls(ByVal oControl As
Control)
Dim frmCtrl As Control
oArrayList = New ArrayList
For each frmCtrl in
oControl.Controls
If TypeOf frmCtrl Is
TextBox Then
oArrayList.Add(New UtilityObj(frmCtrl.ID, directcast(frmCtrl,
TextBox).Text))
End If
If frmCtrl.HasControls Then
LoopingControls(frmCtrl)
End If
Next
End Sub
Conclusion
In
this article, we have seen how to loop through controls in a web page and check
whether it is text box and do some operations based on that. Same concept can
be applied to any controls, so instead of textbox control you need to look for
that control in this control collection. You shouldnt unnecessarily loop
through page Controls collection as it contains unnecessary controls like
"body" tag. If you know from which control you need to loop through, you should
pass that control to this generic function.
|