0

I am receiving an "Object reference not set to an instance of an object" error in my code. I believe I understand why this hapens but I do not know how to get around it. Here is my code:

public string GetLastPost(int subCatId)
{
    SqlConnection conn = null;
    string postDate = null;
    try
    {
        conn = new SqlConnection();
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        conn.Open();

        SqlCommand cmd = new SqlCommand();

        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "forum_GetLastPostDate";
        cmd.Parameters.Add("@SubCategoryId" , subCatId);
        postDate = cmd.ExecuteScalar().ToString();
    } 

This is my SQL query:

SELECT TOP 1 PostDate
FROM forum_posts
WHERE forum_posts.SubcategoryId = @SubCategoryId
ORDER BY PostId desc

The error gets thrown by this line:

postDate = cmd.ExecuteScalar().ToString();

While debugging I noticed that this happens only when the SQL query return nothing. This method gets run multiple times, and the first time it runs it runs correctly because it returns an item. But the second time, because it has no items to return, it throws the error I mentioned.

How can I solve this problem?

Andriy M
  • 76,112
  • 17
  • 94
  • 154
Nistor Alexandru
  • 5,309
  • 9
  • 46
  • 71
  • 3
    remove the `ToString()` on the `ExecuteScalar()` and check for the null return. (place it first on an object). – Aristos Jan 02 '13 at 16:11
  • possible duplicate of [ExecuteScalar throws NullReferenceException](http://stackoverflow.com/questions/559632/executescalar-throws-nullreferenceexception) – DocMax Jan 02 '13 at 17:34

2 Answers2

4

You can use like this

   var data= cmd.ExecuteScalar();
   if(data!=null)
         postDate =data.ToString();

Detail

ExecuteScalar throws NullReferenceException

Community
  • 1
  • 1
शेखर
  • 17,412
  • 13
  • 61
  • 117
0

This will fix your problem... Replace postDate = cmd.ExecuteScalar().ToString(); with

object postdate = cmd.ExecuteScalar();
if (postdate != null)
{
string getUserName = postdate.ToString();
}
Srinivas
  • 1,063
  • 7
  • 15