用户代码消息未处理空引用异常

时间:2013-01-05 14:57:45

标签: c# asp.net nullreferenceexception

我有这个ASPX代码:

<form name="AddArticle" action="Register.aspx" method="post">
<b>
title :<br /></b><input id="Text1" type="text" name="ArticleTitle"/><p></p>
<b>

date: <br /></b><input id="Text2" type="text" name="ArticleDate"/><p></p>

<b>
author : <br /></b><input id="Text3" type="text" name="ArticleAuthor"/><p></p>
<b>
text: <br /></b> <textarea rows="10" cols="60"  name="ArticleBody"></textarea>
<br />
<input id="Reset1" type="reset" value="clean" />
<input id="Submit1" type="submit" value="send" /></form>

这个C#代码:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;

public partial class Register : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        string ArticleTitle, ArticleBody, ArticleAuthor, ArticleDate;
        if (IsPostBack ==false)
        {
            ArticleTitle = Request.Form["ArticleTitle"].ToString();
            ArticleDate = Request.Form["ArticleDate"].ToString();
            ArticleAuthor = Request.Form["ArticleAuthor"].ToString();
            ArticleBody = Request.Form["ArticleBody"].ToString();


            string dpath = Server.MapPath(@"App_Data") + "/MySite.mdb";
            string connectionstring = @"Data source='" + dpath + "';Provider='Microsoft.Jet.OLEDB.4.0';";
            OleDbConnection con = new OleDbConnection(connectionstring);
            string QuaryString = string.Format("insert into tblArticles(ArticleTitle, PostDate) values ('{0}','{1}')", ArticleTitle, ArticleDate);
            OleDbCommand cmd = new OleDbCommand(QuaryString, con);
            con.Open();
            cmd.ExecuteNonQuery();
        }
        else
        {

        }
    }


}

问题在于,我收到此错误消息:

  

System.NullReferenceException未被用户代码
处理   Source =“App_Web_cebzruil”StackTrace:

在这些行中

ArticleTitle = Request.Form["ArticleTitle"].ToString();
ArticleDate = Request.Form["ArticleDate"].ToString();
ArticleAuthor = Request.Form["ArticleAuthor"].ToString();
ArticleBody = Request.Form["ArticleBody"].ToString();

我的问题是如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

表格值可能为空。

尝试插入一个简单的if语句:

if(Request.Form["ArticleTitle"]!=null)
 ArticleTitle = Request.Form["ArticleTitle"].ToString();

你也可以使用try和catch,但在这种情况下不推荐

try
{
   ArticleTitle = Request.Form["ArticleTitle"].ToString();
}
catch(NullReferenceException ex)
{
}