Reply to comment
System.Web.UI.Page find a control by type
Submitted by Ben Hodson on Tue, 03/18/2008 - 19:54
There's not a lot of information on how to find a control by it's type. Of course, most of us know you can find a control by it's "ID" property with the Page object's public method "FindControl()". Here's an example of how to do that:
// find a control on the page by it's IDstring sIdToFind = "RequiredFieldValidator1";
// use the FindControl() and pass the ID to search forSystem.Web.UI.Control controlToFind = page.FindControl(sIdToFind);
// check if the control is nullif (controlToFind != null)
{ // cast the control to a temp objectRequiredFieldValidator rfvTemp = (RequiredFieldValidator)controlToFind;
// now you can access properties of this control like ControlToValidate string sToValidate = rfvTemp.ControlToValidate;}
But what if you don't know the ID of the control your searching for but you DO know the data type? You can loop the control collection and check the type of the controls and access other properties of your control using the C# "is" keyword and the Page's built in control collection. Here's a sample to search for a RequiredFieldValidator by type even if you don't know it's ID:
// loop the page controls collectionfor (int i = 0; i < page.Controls.Count; i++)
{ // use the C# "is" keyword to check the control against a known control typeif (page.Controls[i] is RequiredFieldValidator)
{ // the control IS of this type so cast it to a temp objectRequiredFieldValidator rfvTemp = (RequiredFieldValidator)page.Controls[i];
// now you can access properties of this control like ControlToValidate string sToValidate = rfvTemp.ControlToValidate;}
}
For more information on the C# "is" keyword, look at the is (C# Reference).
Reply
Popular Articles
Last viewed:
- Fix for Firefox click() event issue
- Data Access Layer using SqlDataReader and C# - Code Explanation
- SQL Script to Create and Update a Database
- C# Download File with Progress Bar
- Tutorial for Configuring Silverlight 4, Entity Framework and WCF RIA Services in Separate Component Assemblies (DLL’s)
- Connecting to SQL Server, Oracle, and MySQL with Database or Windows Authentication

Recent comments
13 hours 57 min ago
1 day 13 hours ago
3 days 14 hours ago
4 days 4 hours ago
4 days 15 hours ago
4 days 20 hours ago
5 days 40 min ago
1 week 21 hours ago
1 week 1 day ago
1 week 4 days ago