繁体   English   中英

无效的强制转换异常C#ASP.Net

[英]Invalid cast exception C# ASP.Net

foreach(Label l in Controls)    // setting all labels' s visbility  on page to true
     l.Visible =true;

但在运行时,我遇到了以下错误

Unable to cast object of type 'ASP.admin_master' to type 'System.Web.UI.WebControls.Label'.

如果其中一个控件不是标签类型,您将收到该错误。

你可以尝试:

foreach(Label l in Controls.OfType<Label>())
{
    l.Visible = true;
}

如果要将页面上的所有标签设置为可见,则需要递归函数。

private void SetVisibility<T>(Control parent, bool isVisible)
{
    foreach (Control ctrl in parent.Controls)
    {
        if(ctrl is T)
            ctrl.Visible = isVisible;
        SetVisibility<T>(ctrl, isVisible);
    }
}

用法:

SetVisibility<Label>(Page, true);

检查当前“l”是否具有所需的目标类型:

foreach(control l in Controls) {
    if(l is System.Web.UI.WebControls.Label)
        l.Visible = true;
}
foreach(Control l in Controls)    
        if (l is Label)    l.Visible =true;

如果你想在所有层次结构中:

  public static void SetAllControls( Type t, Control parent /* can be Page */)
    {
        foreach (Control c in parent.Controls)
        {
            if (c.GetType() == t) c.Visible=true;
            if (c.HasControls())  GetAllControls( t, c);
        }

    }

 SetAllControls( typeof(Label), this);
public void Search(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c.Controls.Count > 0)
                Search(c);
            if (c is Label)
                c.Visible = false;
        }
    }

Search(this.Page);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM