Looping Through Controls in ASP.NETLooping Through Controls in ASP.NET
In my recent development I have badly needed to read all the controls from asp.net page. After searching I have found lots of solution. Now I want share with you one of these solution. In this solution we read all the control from asp.net page with out using master page.
**Remember to add namespace System.Collections.Generic
Code: C#
private static Control FindControlIterative(Control root, string id)
{
Control ctl = root;
LinkedList ctls = new LinkedList();
while (ctl != null)
{
if (ctl.ID == id)
return ctl;
foreach (Control child in ctl.Controls)
{
if (child.ID == id)
return child;
if (child.HasControls())
ctls.AddLast(child);
}
ctl = ctls.First.Value;
ctls.Remove(ctl);
}
return null;
}
Code: VB.net
Private Shared Function FindControlIterative(ByVal root As Control, ByVal id As String) As Control
Dim ctl As Control = root
Dim ctls As LinkedList(Of Control) = New LinkedList(Of Control)
Do While (ctl IsNot Nothing)
If ctl.ID = id Then
Return ctl
End If
For Each child As Control In ctl.Controls
If child.ID = id Then
Return child
End If
If child.HasControls() Then
ctls.AddLast(child)
End If
Next
ctl = ctls.First.Value
ctls.Remove(ctl)
Loop
Return Nothing
End Function
Read Control when use Master Page:
And this is where things get a bit tricky with MasterPages. The problem is that when you use MasterPages the page hierarchy drastically changes. Where a simple this.FindControl() used to give you a control instance you now have to drill into the container hierarchy pretty deeply just to get to the content container.
Code:C#
public static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
You can use this method this way..
this.lblError = FindControlRecursive(this.Master,"lblError") as Label;
Thanks,