0

我试图从 aspx 页面中找到标签控件。

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

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

它返回对象引用异常。

并且标签控件位于更新面板中,这可能是问题所在。

4

3 回答 3

0

只需检查是否为空。始终检查空条件,以免最终显示对象引用错误。

if (labelmessageupdate != null)
{
     labelmessageupdate.Text ="something"
}
于 2011-02-16T11:43:45.030 回答
0

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

使用

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;
} 
于 2011-02-16T12:07:28.577 回答
0

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

if(FindControl("updateMessage1") is Label)
{
    labelmessageupdate = FindControl("updateMessage1") as Label;
    labelmessageupdate.Text="This shoould work if available";
}
于 2011-02-16T11:47:37.677 回答