【问题标题】:asp.net object reference not set errorasp.net 对象引用未设置错误
【发布时间】:2011-02-16 11:36:41
【问题描述】:

我正在尝试从 aspx 页面中查找标签控件。

Label labelmessageupdate;
          labelmessageupdate = (System.Web.UI.WebControls.Label )FindControl("updateMessage1");

如果我设置labelmessageupdate.Text ="something"

它返回对象引用异常。

标签控件在更新面板中可能是问题所在。

【问题讨论】:

    标签: asp.net findcontrol


    【解决方案1】:

    只检查空值。始终检查 null 条件,以免最终显示对象引用错误。

    if (labelmessageupdate != null)
    {
         labelmessageupdate.Text ="something"
    }
    

    【讨论】:

      【解决方案2】:

      我认为它找不到您指定的标签控件

      if(FindControl("updateMessage1") is Label)
      {
          labelmessageupdate = FindControl("updateMessage1") as Label;
          labelmessageupdate.Text="This shoould work if available";
      }
      

      【讨论】:

      • 似乎没有找到控件。我使用了上述但没有返回
      • 标签控件在更新面板中会是问题吗?
      • 我不太确定,试试面板的FindControl
      【解决方案3】:

      试试这个,你试图找到的控件可能在另一个用户控件中。

      使用

      Label updateMessage = FindChildControl<Label>(base.Page, "updateMessage1");
      if (updateMessage!=null) 
      {
         updateMessage.Text = "new text";
      }
      
      /// <summary>     
      /// Similar to Control.FindControl, but recurses through child controls.
      /// Assumes that startingControl is NOT the control you are searching for.
      /// </summary>
      public static T FindChildControl<T>(Control startingControl, string id) where T : Control
      {
          T found = null;
      
          foreach (Control activeControl in startingControl.Controls)
          {
              found = activeControl as T;
      
              if (found == null || (string.Compare(id, found.ID, true) != 0))
              {
                  found = FindChildControl<T>(activeControl, id);
              }
      
              if (found != null)
              {
                  break;
              }
          }
      
          return found;
      } 
      

      【讨论】:

      • 嗨,Jason,由于某种原因,它没有找到控件。标签控件在更新面板中可能是问题吗?
      • 你确定标签上有runat="server"吗?
      猜你喜欢
      • 2011-02-08
      • 2011-02-25
      • 1970-01-01
      • 2012-02-03
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      相关资源
      最近更新 更多