2014-10-10 104 views
0

我想設置一個標籤來顯示發生錯誤時的一些文本。當我發生這個錯誤時,標籤會拋出一個NullReferenceException異常。定義Label.Text導致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標籤。我嘗試刪除,然後手動重新生成設計無濟於事。

+0

您錯過了'runat =「server」'。 – 2014-10-10 17:07:03

+0

將runat =「server」添加到標籤標籤會導致大約6個錯誤。 – Frayt 2014-10-10 17:12:17

+0

我創建了一個簡單的Web應用程序,並添加了您擁有的內容,以及一個'runat =「server」'。我必須將代碼更改爲'lblError.InnerText',因爲它是aspx.designer.cs文件中的'HtmlGenericControl'。你可能打算使用''而不是'

回答

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

解決了NullReferenceError異常,但它不更新標籤的文本。標籤文本就是放入標記的內容。 – Frayt 2014-10-10 17:20:41

+0

@Frayt看到我的編輯 – meda 2014-10-10 17:23:15

+0

謝謝,不敢相信我沒有意識到這一點! – Frayt 2014-10-10 17:37:11

相關問題