C# 定义Label.Text会导致NullReferenceException

C# 定义Label.Text会导致NullReferenceException,c#,asp.net,labels,C#,Asp.net,Labels,我正在尝试设置一个标签,以便在出现错误时显示一些文本。当我发生此错误时,标签抛出NullReferenceException 以下是标签。代码背后的文本代码: if (userEmail != null) { //If the same email exists pnlError.Visible = Visible; lblError.Text = "Error: The em

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

以下是标签。代码背后的文本代码:

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>

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

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

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>

您缺少runat=server。将runat=server添加到标签标记会导致大约6个错误。我创建了一个简单的web应用程序,并添加了您拥有的内容以及一个runat=server。我不得不将代码更改为lblError.InnerText,因为它是aspx.designer.cs文件中的HtmlGenericControl。您是否打算使用而不是?来解决NullReferenceError异常,但它不会更新标签的文本。标签文本就是放在标记中的任何内容。谢谢,真不敢相信我没早点意识到这一点!
<asp:Label ID="lblError" runat="server" ></asp:Label>
pnlError.Visible = Visible;
lblError.Text = "Error: The email you have entered......";