0

我有这个 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();

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

4

1 回答 1

2

可能表单值为空。

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

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

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

try
{
   ArticleTitle = Request.Form["ArticleTitle"].ToString();
}
catch(NullReferenceException ex)
{
}
于 2013-01-05T15:02:15.110 回答