定义Label.Text会导致NullReferenceException

时间:2014-10-10 17:03:13

标签: c# asp.net labels

我正在尝试设置标签以在发生错误时显示某些文本。当我发生此错误时,标签会抛出NullReferenceException。

这是后面代码中的label.Text代码:

if (userEmail != null)
            {
                //If the same email exists
                pnlError.Visible = Visible;
                lblError.Text = "Error: The email you have entered is already assigned to an account.";

}

当我构建时,我没有错误,这会告诉我它能够在ASPX代码中找到它。

这是标记:

<asp:Panel ID="pnlError" runat="server" Visible="false" EnableViewState="false">
       <label id="lblError"></label>
        </asp:Panel>

正如您所见,它被包裹在一个面板中。我可以在与Label.Text

相同的功能中更改面板的可见性

这里它是在aspx.designer.cs中定义的:

protected global::System.Web.UI.WebControls.Panel pnlError;
    protected global::System.Web.UI.WebControls.Label lblError;

值得一提的是,每当我更改标记中的任何其他WebControl元素(例如按钮或面板)时,aspx.design.cs都会重新生成,但它不能包含lblError标签。我尝试删除然后手动重新生成设计无济于事。

1 个答案:

答案 0 :(得分:0)

由于标签位于面板内,您需要找到它:

if (userEmail != null)
{
    //If the same email exists
    pnlError.Visible = Visible;
    var lblError= ((Label)(pnlError.FindControl("lblError")));
    if(lblError != null)
    {
        lblError.Text = "Error: The email you have entered......";
    }
}

修改

你最好使用asp控件

<asp:Label ID="lblError" runat="server" ></asp:Label>

然后你不需要找到它

pnlError.Visible = Visible;
lblError.Text = "Error: The email you have entered......";