【问题标题】:Invalid cast exception C# ASP.Net无效的强制转换异常 C# ASP.Net
【发布时间】:2012-09-21 12:36:45
【问题描述】:
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'.

【问题讨论】:

    标签: c# asp.net casting


    【解决方案1】:
    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);
    

    【讨论】:

      【解决方案2】:
      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 主要标签可见!你想要页面中的所有标签吗? (在所有层次结构中?)
      • ryt 现在我正在处理一个具有九个标签的简单 Web 表单。层次结构对所有人都是一样的。
      • 你需要删除controls =
      【解决方案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”。
      • 可以添加一个额外的检查( hasControls )看我的回答。 :-)
      • @RoyiNamir 没关系,因为它不会进入没有孩子的 for 循环。
      • 确实很重要 - 你正在打开一个新的递归实例。如果它没有孩子,为什么要把它发送到一个函数?
      • @RoyiNamir 我的意思是添加检查没有错,但它不会对性能产生任何可衡量的影响。
      【解决方案4】:

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

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

      【讨论】:

        【解决方案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." 这意味着如果我在同一页面上有其他控件,例如文本框和按钮,那么我应该使用它..ryt 吗?如果我错了,请纠正我。而且这段代码不起作用。
        • 此代码至少需要 .Net 3.5 并且您的代码文件顶部有 using System.Linq;。除此之外应该没问题。
        猜你喜欢
        • 2012-02-20
        • 1970-01-01
        • 2012-05-28
        • 2021-11-14
        • 1970-01-01
        • 2015-01-27
        • 2012-09-20
        • 2013-11-06
        • 1970-01-01
        相关资源
        最近更新 更多