Click here to Skip to main content
15,893,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
--Default.aspx--

XML
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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">
    <asp:Button ID="Button1" runat="server" Height="30px"
        Text="Button" Width="69px" onclick="Button1_Click"  />
    <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
    <div>

    </div>
    </form>
</body>
</html>


--Default.aspx.cs--
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public delegate void Y();

public partial class _Default : System.Web.UI.Page 
{ 
    public event Y X;
    protected void Page_Load(object sender, EventArgs e)
    {
        A a = new A();
        X += a.f;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        X();
    }
}

public class A:_Default
{
    public void f()
    {
        TextBox1.Text = "success";
    }
}


1)why TextBox1.Text="success" will generate a NullReferenceException in function f() when run Default.aspx and click Button on browser.
Posted
Updated 1-Jun-10 22:03pm
v5

1 solution

Because you just create an instance of class _Default but the controls in it don't get instantiated. This is what the ASP.NET engine does when you request a page.

This page may help you: http://www.west-wind.com/weblog/posts/120530.aspx[^]
 
Share this answer
 
Comments
shilf 2-Jun-10 3:50am    
if the function Button1_Click(object sender, EventArgs e) is :
            protected void Button1_Click(object sender, EventArgs e)  
            {        
                           TextBox1.Text="success";    
            }

you said"you just create an instance of class _Default but the controls in it don't get instantiated"
why it is right, when i click the button 
kornakar 2-Jun-10 5:27am    
You have TWO different instances of the page, the one you're clicking the button on, and the another you create manyally on Page_Load. The one you see on your browser is initialized by ASP.NET engine and that's why the TextBox1 has an instance. However, the class A is just manyally created and doesn't get initialized (TextBox1 is null). I suggest you to read a few articles about classes and references etc.
shilf 2-Jun-10 10:24am    
I see,thanks for your help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900