简体   繁体   中英

Invalid cast exception C# ASP.Net

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

But on running ,i am getting following error

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

If one of the controls is not of type label, you'll get that error.

You could try:

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

If you want the set all labels on the page to visible you need a recursive function.

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);
    }
}

Usage:

SetVisibility<Label>(Page, true);

Check if the current "l" has the required destination type:

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;

if you want in all hierarchy :

  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;
        }
    }

and

Search(this.Page);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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