NullReferenceException - 无法弄清楚为什么初始化对象重置为null

时间:2011-12-19 21:54:31

标签: c# asp.net

好的,我的代码隐藏文件中有以下类。它是一个非常简单的页面,只需获取TestIssue对象,将条目加载到文本框中以编辑条目,然后单击保存时,它将调用更新数据库中TestIssue的函数。

这是代码。

public partial class Issues_Edit : System.Web.UI.Page
    {
        protected string filter_test_director;
        protected TestIssue myIssue;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string id = Request.QueryString["id"];  

                id = "1358";
                myIssue = new TestIssue(Convert.ToInt32(id));

                issue_date.Text = myIssue.Entry_Date.ToString();
                issue_author.Text = myIssue.Author.Full_Name_RFL;

                issue_text.Text = myIssue.Entry.Replace("<br>", "\n");
                issue_text.Height = 150;
                issue_text.Width = 400;

            }

        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            myIssue.Entry = issue_text.Text;

            int update  = TestIssueDB.UpdateIssue(myIssue);

            if (update == 1)
            {
                //Response.Redirect("program.aspx?p=" + myIssue.Program_ID);
            }
            else
            {
                top_message.Text = "Error Updating Issue Text";
            }

        }

    }

现在的问题是,当调用Save函数时,它会在myIssue对象上出现nullreferenceexception错误。我不确定为什么会这样,因为它与我在其他页面上处理其他对象的方式完全相同,对象在page_load上面声明,在page_load中初始化,然后在其他函数中修改。

知道为什么myIssue对象在该函数中不存在?

1 个答案:

答案 0 :(得分:6)

单击按钮时,您永远不会初始化该变量!

每个页面请求都会创建一个新的页面实例。通常,您在上一个请求期间所做的任何操作都不会对当前请求产生任何影响。特别是,您在第一个请求上设置了myIssue字段,但在第二个请求中,IsPostBack为真,因此您的初始化代码不会被执行。

相关问题