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?