标签控件抛出system.nullreferenceexception

编程入门 行业动态 更新时间:2024-10-26 05:18:28
本文介绍了标签控件抛出system.nullreferenceexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是ASP.Net的新手,并坚持使用我的第一个程序。我的标签抛出以下异常:(

I am new to ASP.Net and stuck with my First program itself. My label is throwing the following Exception :(

System.NullReferenceException: 'The object reference was not set to an object instance.'

) 我的设计器页面的Label如下: -

) My designer page has the Label as follows:-

protected global::System.Web.UI.WebControls.Label lblmsg;

有人可以帮我,我出错了。 我尝试过: 这是我的 firstpage.aspx

Could someone help me, where I am going wrong. What I have tried: Here is my firstpage.aspx

<pre><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FirstPage.aspx.cs" Inherits="WebApplicationDemo.FirstPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="www.w3/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%Response.Write("HeLLo World"); %> <asp:label ID="lblmsg" runat="server"/> <asp:Button Text="Go to Second Page" runat="server" OnClick="BtnGOTOSECOND_Click"/> </div> </form> </body> </html>

这是我的 firstpage.aspx.cs

Here is my firstpage.aspx.cs

<pre>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.OleDb; using System.Data; namespace WebApplicationDemo { public partial class FirstPage : System.Web.UI.Page { public FirstPage() { lblmsg.Text = "My First Label"; } protected void BtnGOTOSECOND_Click(object sender, System.EventArgs e) { Response.Redirect("SecondPage.aspx"); } } }

推荐答案

您正在尝试从构造函数访问该控件。此时尚未创建控制树。 您可以访问控件的绝对最早点是在基数 FrameworkInitialize 方法: You're trying to access the control from the constructor. The control tree has not been created at that point. The absolute earliest point you can access the controls is after the base FrameworkInitialize method has been invoked: protected override void FrameworkInitialize() { base.FrameworkInitialize(); // The control tree has now been created. }

这通常发生在 Init 事件之前,所以这通常是这类代码的最佳位置。

This typically happens just before the Init event, so that's usually the best place for this sort of code.

lblmsg = new Label(); lblmsg.Text = "My First Label";

更多推荐

标签控件抛出system.nullreferenceexception

本文发布于:2023-11-17 03:23:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控件   抛出   标签   nullreferenceexception   system

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!