标签控件抛出system.nullreferenceexception [英] Label control throws system.nullreferenceexception

查看:66
本文介绍了标签控件抛出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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆