Search code examples
asp.netcastingwebformsfindcontroldynamic-controls

ASP.net Cast FindControl output to a parameter


I want to cast the output of FindControl method to a control of a specific type but I want the type itself being passed as an argument. I first tried:

public static List<T> GetList<T>(..., Type tp, ...)
{
...
tp castedCtrl = (panel.FindControl(ctrlPrefixName + i.ToString()) as tp);
...
}

This is my preferred result but doesn't compile at all. I also tried :

dynamic castedCtrl = Convert.ChangeType(panel.FindControl(ctrlPrefixName + i.ToString()), tp);

but this requires all my tp 's implement IConvertible interface which is not desired and required a lot of unintended work.

How can I cast the output of FindControl output to my desired type (which in action I want to pass the name of a user control class).


Solution

  • Here you go:

    public static List<T> GetList<T, U>(Page page, string ctrlPrefixName) 
       where T : class 
       where U : Control
    {
       int i = 1;
       U castedCtrl = page.FindControl(ctrlPrefixName + i.ToString()) as U;
       return new List<T>();
    }
    

    In order to use it:

    GetList<MyType, DropDownList>(this, "MyControl_");