mmssaann
mmssaann

Reputation: 1507

Unable to convert webcontrol to generic type in asp.net c#

I have the below method that I am using to create webcontrols (for now just literal and Panel)

private T CreateControl<T>(string s1, string s2, string m1)
    where T: WebControl , new()
{
    T ctrl = default(T);

   if (ctrl is Literal )
    {
       Literal l = new Literal();
       l.ID = s1 + "ltl" + s2;
       l.Text = s1 +  " " + s2;
       ctrl = (Literal)l;
    }
    else if (ctrl is Panel)
    {
        Panel p  = new Panel();
        p.ID = s1+ "pnl" + s2;
        p.CssClass = s1 + "graphs";
        p.Attributes.Add("responsefield", s2);
        p.Attributes.Add("metricid", m1);
        ctrl = (Panel)l;

    }
    else if (ctrl is CheckBox)

       return ctrl;
}

I am invoking this as:

Literal lg = CreateControl<Literal>("emails", name.Name, name.MetricId.ToString() );

But the conversion is failing at:

ctrl = (Literal)l;
ctrl = (Panel)p;

Error:

Cannot implicitly convert type 'System.Web.UI.WebControls.Panel' to 'T' 

Can somebody advise how to handle this conversion?

Thanks in advance...

Upvotes: 1

Views: 521

Answers (1)

&#214;zg&#252;r Kaplan
&#214;zg&#252;r Kaplan

Reputation: 2136

I can suggest you something like this.

private T CreateControl<T>(string s1, string s2, string m1)
where T : System.Web.UI.Control,new()
{

    if (typeof(T) == typeof(Literal))
    {
        Literal l = new Literal();
        l.ID = s1 + "ltl" + s2;
        l.Text = s1 + " " + s2;
        return l as T;
    }
    else if (typeof(T) == typeof(Panel))
    {
        Panel p = new Panel();
        p.ID = s1 + "pnl" + s2;
        p.CssClass = s1 + "graphs";
        p.Attributes.Add("responsefield", s2);
        p.Attributes.Add("metricid", m1);
        return p as T;

    }
    else if (typeof(T) == typeof(CheckBox))
    {
        return new CheckBox() as T;
    }
    else
    {
        return new T();
    }
}

Edit: Modified the method you don't need to cast it afterwars like @jbl suggested.

Literal l = CreateControl<Literal>("something", "something", "something");

Upvotes: 2

Related Questions