簡體   English   中英

定義Label.Text導致NullReferenceException

[英]Defining Label.Text leads to a NullReferenceException

我正在嘗試設置一個標簽,以在發生錯誤時顯示一些文本。 當我使此錯誤發生時,標簽將引發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標簽。 我嘗試刪除然后手動重新生成設計無濟於事。

由於標簽位於面板內部,因此需要找到它:

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......";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM