Reply to comment

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 ID
string sIdToFind = "RequiredFieldValidator1";
 
// use the FindControl() and pass the ID to search for
System.Web.UI.Control controlToFind = page.FindControl(sIdToFind);
 
// check if the control is null
if (controlToFind != null)
{
    // cast the control to a temp object
    RequiredFieldValidator 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 collection
for (int i = 0; i < page.Controls.Count; i++)
{
    // use the C# "is" keyword to check the control against a known control type
    if (page.Controls[i] is RequiredFieldValidator)
    {
        // the control IS of this type so cast it to a temp object
        RequiredFieldValidator 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