3
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'.

4

5 回答 5

5

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

你可以试试:

foreach(Label l in Controls.OfType<Label>())
{
    l.Visible = true;
}
于 2012-09-30T09:20:55.950 回答
3

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

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);
于 2012-09-30T09:32:00.937 回答
0

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

foreach(control l in Controls) {
    if(l is System.Web.UI.WebControls.Label)
        l.Visible = true;
}
于 2012-09-30T09:22:46.703 回答
0
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);
于 2012-09-30T09:23:10.667 回答
0
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);
于 2012-09-30T09:49:31.343 回答