1.
public partial class Student : System.Web.UI.Page
{
    protected Student student;    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            student= new Student(100000);
            txtName.Text=student.Name;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        student.Name=txtName.Text;
        student.Update();
    }
}
//如果是这样 就会提示: 未将对象引用设置到对象的实例。 2.
public partial class Student : System.Web.UI.Page
{
    protected Student student;    protected void Page_Load(object sender, EventArgs e)
    {
            student= new Student(100000);
            txtName.Text=student.Name;
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        student.Name=txtName.Text;
        student.Update();
    }
}//不会提示 未将对象引用设置到对象的实例。 但更新不了
3.
public partial class Student : System.Web.UI.Page
{
    protected Student student;    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            student= new Student(100000);
            txtName.Text=student.Name;
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        student= new Student(100000);
        student.Name=txtName.Text;
        student.Update();
    }
}//正常运行了请解释这3种情况的原因

解决方案 »

  1.   

    btnSubmit按钮点击的时候  是先Page_Load 再执行 Click里的事件的试试将   student= new Student(100000);  放在构造函数中
      

  2.   

    ~~rs
    另,建议lz看下.net相关的页面生存周期
      

  3.   

    1.显然在点击按钮的时候由于Page_load中的方法进不去了,所以就没有初始化了,当然就是null了
    2.其实已经更新了,那为什么更新不了呢,因为在点击按钮的时候进入了page_load,并且你又把txtName.Text=student.Name;等于把旧的数据又写回去了,你的改变没有奏效,然后你再提交的时候,数据是和数据库里一样的,所以更新不了
    3.少掉了步骤2中的错误情况,又在后面重新提取了Student,当然就OK了。但是写法仍然不好。就你这个写法稍作改进:public partial class Student : System.Web.UI.Page
    {
        protected Student student;    protected void Page_Load(object sender, EventArgs e)
        {
            student= new Student(100000);
            if (!IsPostBack)
            {
                txtName.Text=student.Name;
            }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            student.Name=txtName.Text;
            student.Update();
        }
    }
      

  4.   

    一个小问题,引出了关于ASP.NET的一个最基本的知识点:页面的生命周期。还有两个基本概念:回发和回传。
      1、当你发出请求到页面Render到客户端,一个页面完成了它的生命周期,并在服务端释放了他的所有资源,例如当页面呈现(render)完后,你的 Student就会释放掉(就不从在了)。2、那么页面在什么时候执行if(!IsPostBack){ }中的内容呢?并不是每次都执行。当第一次请求页面时会执行if(!IsPostBack){ }之中的代码。这个就是我们通常所说的回发和回传的问题。
      

  5.   

    3楼的分析的有道理,注意下IsPostBack的用法