开发者

Unable to caste a control type to 'System.Web.UI.Webcontrols.Lable type

开发者 https://www.devze.com 2023-01-27 10:26 出处:网络
I have this generic function T AddControl<T>() where T : WebControl, new() { T ctrl = new T();

I have this generic function

T AddControl<T>() where T : WebControl, new() { 
T ctrl = new T(); 
if (ctr开发者_如何学Pythonl is Label)  {((Label)ctrl).Text = "FirstName :";}
return ctrl; } 

I get the error: "Cannot convert Type 'T' to 'System.Web.UI.Webcontrols.Lable'" What would be the proper way of casting. Thanks in advance. BB


You can use as instead:

T AddControl<T>() where T : WebControl, new() { 
    T ctrl = new T();
    Label label = ctrl as Label;
    if (label != null)
    {
        label.Text = "FirstName :";
    }
    return ctrl; 
}
0

精彩评论

暂无评论...
验证码 换一张
取 消