2014-10-10 105 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

相关问题