Nave Tseva
Nave Tseva

Reputation: 878

Null Reference Exception was unhandled by user code Message

I have this ASPX code:

<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>

And this C# code:

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
        {

        }
    }


}

The problem here is, I get this error message:

System.NullReferenceException was unhandled by user code
Source="App_Web_cebzruil" StackTrace:

In those lines

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

My question is how can I fix this problem?

Upvotes: 0

Views: 7746

Answers (1)

Norbert Pisz
Norbert Pisz

Reputation: 3440

Probably form values are null.

Try to insert a simple if statement:

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

You can also use try and catch but is not recomended in this case

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

Upvotes: 2

Related Questions