I am a danish programmer living in Bangkok.
Read more about me @ rasmus.rummel.dk.
Webmodelling Home > ASP.NET > C# Utility Functions > Control - FindControls

FindControls

In case you have a Control container containing controls of different types, you may be interested in finding all controls of a specific type - this is what FindControls is for.

Usage

  • Example
    • I use the FindControls function in a Favourite Design customer website kmddc.go.th to find all RadioButtons within a container.
  • Example Code
    • PlaceHolder phContainer = new PlaceHolder(); //imagine this PlaceHolder filled with controls
      List<RadioButton> rbtAnswers = Utils.Control.FindControls<RadioButton>(phContainer);
      

The FindControls function :

public static List<T> FindControls<T>(Control pParent) where T : Control
{
	List<T> foundControls = new List<T>();
 
	FindControls<T>(pParent, foundControls);
 
	return foundControls;
}
 
public static void FindControls<T>(Control pParent, List<T> pFoundControls) where T : Control
{
	foreach (Control c in pParent.Controls)
	{
		if (c is T)
		{
			pFoundControls.Add((T)c);
		}
		else if (c.Controls.Count > 0)
		{
			FindControls<T>(c, pFoundControls);
		}
	}
}

Comments

You can comment without logging in
Profile
Username
Password
Password
Email
Nickpic
Get notified on reply to own posts  (only works if you specify an email address)
Get notified on receiving a PM  (only works if you specify an email address)
Remember my username
Remember my password
signature
Words: Chars: Chars left: