System.Web.UI.Page find a control by type
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).

Recent comments
8 hours 32 min ago
23 hours 25 min ago
3 days 11 hours ago
4 days 11 hours ago
6 days 12 hours ago
1 week 1 hour ago
1 week 12 hours ago
1 week 18 hours ago
1 week 22 hours ago
1 week 3 days ago