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

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

但是在运行时,我遇到了以下错误: 无法将类型为“ASP.admin_master”的对象强制转换为类型“System.Web.UI.WebControls.Label”。
5个回答

5
如果控件中有一个不是标签类型,您将收到该错误。
您可以尝试:
foreach(Label l in Controls.OfType<Label>())
{
    l.Visible = true;
}

"If one of the controls is not of type label, you'll get that error." 这意味着如果在同一页上还有其他控件,如文本框和按钮,则应该使用它们,对吗?如果我理解有误,请纠正我。此代码不起作用。 - HalfWebDev
这段代码需要至少 .Net 3.5,并且在你的代码文件顶部有 using System.Linq;。除此之外,应该就没问题了。 - Karl-Johan Sjögren

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

@RoyiNamir 在问题中确实说过“将页面上所有标签的可见性设置为true”。 - Magnus
很重要 - 你正在打开一个新的递归实例。如果它没有子节点,为什么要将其发送到函数中? - Royi Namir
@RoyiNamir 我的意思是加上这个检查并没有错,但它不会有任何可衡量的性能影响。 - Magnus
@Magnus 的函数模板让我的工作变得更加轻松了。为此点赞 +1。 - HalfWebDev
@Magnus,我尝试设置“ReadOnly”属性,但“System.Web.UI.Control”没有该定义。还有其他方法吗? - HalfWebDev
显示剩余6条评论

0

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

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

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

@kushal 主要标签将可见!您想在页面中看到所有标签吗?(包括所有层次结构?) - Royi Namir
现在我正在开发一个简单的Web表单,其中包含九个标签。对于所有标签,层次结构都将保持相同。 - HalfWebDev
你需要移除 controls = - Magnus

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接