Recursive FindControl<T>

Need to find a control anywhere on the page or in a template?  Inspired by Steve Smith's implementation, here is the code to find it recursively.  This example assumes the code is located in a custom base page.

 

  1 public T FindControl<T>(string id) where T : Control
  2 {
  3     return FindControl<T>(Page, id);
  4 }
  5 
  6 public static T FindControl<T>(Control startingControl, string id) where T : Control
  7 {
  8     // this is null by default
  9     T found = default(T);
 10 
 11     int controlCount = startingControl.Controls.Count;
 12 
 13     if (controlCount > 0)
 14     {
 15         for (int i = 0; i < controlCount; i++)
 16         {
 17             Control activeControl = startingControl.Controls[i];
 18             if (activeControl is T)
 19             {
 20                 found = startingControl.Controls[i] as T;
 21                 if (string.Compare(id, found.ID, true) == 0) break;
 22                 else found = null;
 23             }
 24             else
 25             {
 26                 found = FindControl<T>(activeControl, id);
 27                 if (found != null) break;
 28             }
 29         }
 30     }
 31     return found;
 32 }       
Published Friday, April 13, 2007 3:05 PM by Palermo4
Filed under: , , ,

Comments

# re: Recursive FindControl<T>

Friday, April 13, 2007 3:32 PM by Steve Smith

What, no link love for me?

# re: Recursive FindControl<T>

Friday, April 13, 2007 5:20 PM by Steve Smith

Woot! Thanks, and nice job on the VB version, too!

# re: Recursive FindControl<T>

Friday, April 13, 2007 5:49 PM by scott cate

Steve Smith is a Link Shore (-s +w)

# re: Recursive FindControl<T>

Saturday, April 14, 2007 4:24 AM by Marcus

Usefull class but why post code with annoying line numbers??? Cut and paste requires each line to be edited!

# re: Recursive FindControl<T>

Monday, April 16, 2007 11:33 AM by Aaron

I couldn't resist trying to simplify this! Hopefully I succeeded :)

http://intrepidnoodle.com/blog/show/18.aspx

# re: Recursive FindControl<T>

Tuesday, April 17, 2007 5:15 AM by Aaron

Hi, I couldn't resist trying to simplify your code somewhat... did I succeed ? http://intrepidnoodle.com/blog/show/18.aspx

# re: Recursive FindControl<T>

Wednesday, April 18, 2007 9:22 PM by Palermo4

Aaron, I did try out your code and it works just fine.  Thanks for the update!

# re: Recursive FindControl<T>

Monday, April 23, 2007 12:01 PM by daCodez

Where do i get the VB Version?

# re: Recursive FindControl<T>

Monday, May 21, 2007 10:30 AM by Raymond Sassine
Is there a VB Version as well?

# Mcse Certification

Wednesday, June 06, 2007 11:13 PM by Mcse Certification

MCSE Certification could help a lot in career advancement in technology field. After the burst of Year 2000 techno. bubbles, most corporations start investing their money into IT again.

# re: Recursive FindControl<T>

Thursday, June 21, 2007 2:50 AM by dotnetnoobie

i made a vb version

Partial Class Default4

   Inherits System.Web.UI.Page

   Public Overloads Function FindControl(Of T As Control)(ByVal id As String) As T

       Return FindChildControl(Of T)(Page, id)

   End Function

   Public Overloads Function FindControl(Of T As Control)(ByVal startingControl As Control, ByVal id As String) As T

       Return ControlFinder.FindControl(Of T)(startingControl, id)

   End Function

   Public Function FindChildControl(Of T As Control)(ByVal startingControl As Control, ByVal id As String) As T

       Return ControlFinder.FindChildControl(Of T)(startingControl, id)

   End Function

   Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

       Me.FindControl(Of RadioButton)(Page, "RadioButton1").Checked = True

   End Sub

End Class

Public NotInheritable Class ControlFinder

   Private Sub New()

       MyBase.New()

   End Sub

   Public Shared Function FindControl(Of T As Control)(ByVal startingControl As Control, ByVal id As String) As T

       Dim found As T = TryCast(startingControl.FindControl(id), T)

       If found Is Nothing Then

           found = FindChildControl(Of T)(startingControl, id)

       End If

       Return found

   End Function

   Public Shared Function FindChildControl(Of T As Control)(ByVal startingControl As Control, ByVal id As String) As T

       Dim found As T = Nothing

       For Each activeControl As Control In startingControl.Controls

           found = TryCast(activeControl, T)

           If found Is Nothing OrElse (String.Compare(id, found.ID, True) <> 0) Then

               found = FindChildControl(Of T)(activeControl, id)

           End If

           If found IsNot Nothing Then

               Exit For

           End If

       Next

       Return found

   End Function

End Class

# Purpose of Blog

Tuesday, July 24, 2007 11:47 AM by Palermo4

I have recently decided to redo tags on my blog . This effort required me to go back in the archives

# Purpose of Blog

Tuesday, July 24, 2007 12:05 PM by Community Blogs

I have recently decided to redo tags on my blog . This effort required me to go back in the archives

# Recursive FindContol (Of T As Control)

Wednesday, July 25, 2007 6:43 PM by Palermo4

I just posted code to allow recursive search for a control anywhere on the page. Here is the VB (Visual

# re: Recursive FindControl<T>

Sunday, November 18, 2007 2:31 PM by Tanveer Badar

Aside from clarity, I like that for loop much better this way:

15         for (int i = 0; i < controlCount; i++)

16         {

17             Control activeControl = startingControl.Controls[i];

18             if ( string.Compare( id , activeControl.Controls [ i ] , true ) == 0 )

19                return activeControl.Controls [ i ] as T;

20             else

21                 return FindControl<T>(activeControl, id);

22         }

Notice, how it avoids the two types casts your version always incurrs even if ID does not match. And there is no need for that redundant if before the loop.

Always run FxCop on your code.

# Simple ASP.NET 2.0 Tips and Tricks that You May (or may not) have Heard About [from dwahlin]

Thursday, January 03, 2008 8:45 PM by Boringlamb

ASP.NET2.0isanawesomeframeworkfordevelopingWebapplications.

# re: Recursive FindControl<T>

Thursday, January 17, 2008 11:01 AM by Zambonilli

I agree with Tanveer this implementation has excessive casting.  Also, there is a reason that this hasn't been added to ASP.net because it is way to expensive of an operation.  But if you must use it why not make it an extension method on the page & control class?

# re: Recursive FindControl<T>

Tuesday, February 12, 2008 3:08 AM by TS

Works good with one drawback,

If I want to find panel inside panel, it will not find it because if will fail on the first panel, or am I wrong?

# re: Recursive FindControl<T>

Tuesday, March 04, 2008 4:43 PM by lol

<a href= http://index1.yourherlad.com >supercalifragilisticexpialidocious</a> <a href= http://index2.yourherlad.com >johnny thompson elvis impersonator itinerary for 2006</a> <a href= http://index3.yourherlad.com >water peru hoax</a> <a href= http://index7.yourherlad.com >dental reseach program</a> <a href= http://index8.yourherlad.com >short nylon nightgowns</a> <a href= http://index6.yourherlad.com >5224 ravens glen nashville tn satellite map</a> <a href= http://index5.yourherlad.com >anthony malione</a> <a href= http://index9.yourherlad.com >goodys</a> <a href= http://index4.yourherlad.com >villanova phd programsn</a> <a href= http://index10.yourherlad.com >2004 dodge ram 1500 truck problems</a>

# re: Recursive FindControl<T>

Tuesday, March 04, 2008 5:00 PM by Olgunka-bt

<a href= http://index1.amilop.com >rose marie mize</a> <a href= http://index2.amilop.com >kmg fachions</a> <a href= http://index9.amilop.com >church 20attire</a> <a href= http://index4.amilop.com >post-it picture paper</a> <a href= http://index5.amilop.com >1970 movie</a> <a href= http://index7.amilop.com >container water gardens</a> <a href= http://index8.amilop.com >wallmart guns</a> <a href= http://index10.amilop.com >chihuahuas</a> <a href= http://index6.amilop.com >vin number key car thief</a> <a href= http://index3.amilop.com >food posening</a>

# re: Recursive FindControl<T>

Tuesday, March 04, 2008 5:00 PM by Olgunka-kh

<a href= http://index8.1ubani.com >dirty fritz</a> <a href= http://index6.1ubani.com >usaturk</a> <a href= http://index5.1ubani.com >block print wedding</a> <a href= http://index4.1ubani.com >tcm modeling</a> <a href= http://index3.1ubani.com >the mariner resort</a> <a href= http://index10.1ubani.com >jenifer anistons breasts</a> <a href= http://index7.1ubani.com >thomasville furniture showroom in southern ca</a> <a href= http://index1.1ubani.com >first financial</a> <a href= http://index2.1ubani.com >sahasrabudhe new jersey</a> <a href= http://index9.1ubani.com >chinese opera doll</a>

# re: Recursive FindControl<T>

Tuesday, March 04, 2008 5:00 PM by Olgunka-kh

<a href= http://index8.1ubani.com >dirty fritz</a> <a href= http://index6.1ubani.com >usaturk</a> <a href= http://index5.1ubani.com >block print wedding</a> <a href= http://index4.1ubani.com >tcm modeling</a> <a href= http://index3.1ubani.com >the mariner resort</a> <a href= http://index10.1ubani.com >jenifer anistons breasts</a> <a href= http://index7.1ubani.com >thomasville furniture showroom in southern ca</a> <a href= http://index1.1ubani.com >first financial</a> <a href= http://index2.1ubani.com >sahasrabudhe new jersey</a> <a href= http://index9.1ubani.com >chinese opera doll</a>

# Three Requests for ASP.NET 4 and VS 2010

Sunday, March 16, 2008 4:45 PM by Community Blogs

I have three things that have been on my wish list for ASP.NET and/or Visual Studio that I&#39;m curious

# re: Recursive FindControl<T>

Tuesday, May 13, 2008 1:25 PM by bmiedlar

else block should be changed to if(found == null) or all children are not processed

# Resell Rights

Wednesday, May 21, 2008 7:57 AM by Resell Rights

Go to Port Sarim, west of Draynor village, and ask one of the people in the blue uniforms to go to Karamja and pay them 30 runescape gp. When you get there, walk off the dock and you should see a house. Enter the house and talk to a man named Luthas.

# Weight loss

Wednesday, May 28, 2008 8:40 AM by Weight loss

Diet Products and Weight Loss Supplements at Discount Prices. Save 50-70% on quality products.

# business income opportunity xango

Thursday, June 26, 2008 8:29 PM by business income opportunity xango

It’ s a well known fact that only a proper designed web site is the key to attract visitors. There are many factors to consider while creating a web site and it is important to remember that your/ your company’ s website is often the first point of contact

# Ab belt

Sunday, June 29, 2008 4:13 AM by Ab belt

cool article

# 你或许还未听说过的一些ASP.NET 2.0要诀

Tuesday, July 08, 2008 11:00 PM by 曹雷

在开发Web应用程序方面,Asp.net是一个令人敬畏的框架。如果你使用过一段时间,那么这就不是什么秘密了。它提供了一些十分强大的新特征,而你只需要些少量的代码就能实现。我曾经列出一个清单,上面是一些...

# re: Recursive FindControl<T>

Tuesday, August 26, 2008 3:35 PM by joemamba4

   Protected Function GetChildControl(ByVal oParentControl As Control, ByVal sChildID As String) As Control

       Try

           Dim oChildControl As Control = Nothing

           For i As Integer = 0 To oParentControl.Controls.Count - 1

               If oParentControl.Controls(i).ID = sChildID Then

                   Return oParentControl.Controls(i)

               Else

                   oChildControl = GetChildControl(oParentControl.Controls(i), sChildID)

                   If oChildControl IsNot Nothing Then Return oChildControl

               End If

           Next

           Return oChildControl

       Catch ex As Exception

           Throw ex

       End Try

# Software Resell Rights

Wednesday, September 03, 2008 11:02 PM by Software Resell Rights

“ The Daily Telegraph has been accused of inserting keywords into copy to ensure its website gets the maximum number of hits, so it was interesting to see the following comment on telegraph. co. uk, posted in response to a rather dry piece about civil

# Recursive FindControl

Monday, September 22, 2008 10:16 AM by Community Blogs

I&#39;ve been asking for a recursive FindControl() method as a method off of System.Web.UI.Control for

# Recursive FindControl

Monday, September 22, 2008 9:57 PM by Readed By Wrocław NUG members

I&#39;ve been asking for a recursive FindControl() method as a method off of System.Web.UI.Control for

# 你或许还未听说过的一些ASP.NET 2.0要诀

Thursday, October 23, 2008 12:00 PM by ‘ 汏壞疍,

在开发Web应用程序方面,Asp.net是一个令人敬畏的框架。如果你使用过一段时间,那么这就不是什么秘密了。它提供了一些十分强大的新特征,而你只需要些少量的代码就能实现。我曾经列出一个清单,上面是一...

# Simple ASP.NET 2.0 Tips and Tricks that You May (or may not) have Heard About

Friday, April 10, 2009 10:28 AM by Dan Wahlin's WebLog

ASP.NET 2.0 is an awesome framework for developing Web applications. If you've worked with it for awhile

# 分享 你或许还未听说过的一些ASP.NET 2.0要诀

Sunday, April 12, 2009 10:31 PM by 广陵散仙(www.cnblogs.com/junzhongxu/)

在开发Web应用程序方面,Asp.net是一个令人敬畏的框架。如果你使用过一段时间,那么这就不是什么秘密了。它提供了一些十分强大的新特征,而你只需要些少量的代码就能实现。我曾经列出一个清单,上面是一些...

# Loose Stomach Fat

Wednesday, November 25, 2009 9:13 PM by Loose Stomach Fat

Weight loss tips ...

# Simple ASP.NET 2.0 Tips and Tricks that You May (or may not) have Heard About &laquo; Infosolution&#039;s Network

Pingback from  Simple ASP.NET 2.0 Tips and Tricks that You May (or may not) have Heard About  &laquo; Infosolution&#039;s Network

# re: Recursive FindControl<T>

Thursday, August 04, 2011 7:35 AM by ultravi0let

That really helped ! Thanks !

# re: Recursive FindControl<T>

Friday, September 30, 2011 12:39 AM by .net follower

Nice post! My own FindControlRecursive helped me out many times. Especially, when I deal with MasterPages. For example, one of such usage is shown in my post here – dotnetfollower.com/.../sharepoint-add-onchange-attribute-to-dropdownchoicefield.

Thank you!

Leave a Comment

(required) 
(required) 
(optional)
(required)