string strmcat = "select idcategory from categories where categorydesc='" + mcategory + "'";
SqlCommand com = new SqlCommand(strmcat, conn);
conn.Open();
Object o = (Object)com.ExecuteScalar();
if ( o != DBNull.Value)
{
idmcat = (int)com.ExecuteScalar();
}
conn.Close();
What wrong with this code.When null values return from db then also control goes in if condition.
How to checkNull values using Execute Scalar
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.

Syed ShakeerRank #777 · 3K reputationPosted Feb 16, 2011, 7:35 PM EST
You can check the object if it is null or not as follows:
Object o = (Object)com.ExecuteScalar();
if ( o != Null)
{
}
Amit ChoudharyRank #145 · 15.8K reputationPosted Feb 16, 2011, 8:29 PM EST
Thanks.
Suthish NairRank #92 · 22.8K reputationPosted Feb 17, 2011, 10:30 AM EST
ExecuteScalar returns null if no value is returned, and DBNull.Value if a null is returned.
Pankaj,
So try like this..