I want to fetch 1st row 1st cell value from database it works well with below code . But when there is no result found it throws Exception.
How to handle with DBNull .
Should i change my query ? which return some value if theirs no record ?
System.NullReferenceException: Object reference not set to an instance of an object.
Code:
public string absentDayNo(DateTime sdate, DateTime edate, string idemp)
{
string result="0";
string myQuery="select COUNT(idemp_atd) absentDayNo from td_atd where ";
myQuery +=" absentdate_atd between '"+sdate+"' and '"+edate+" ";
myQuery +=" and idemp_atd='"+idemp+"' group by idemp_atd ";
SqlCommand cmd = new SqlCommand(myQuery, conn);
conn.Open();
//System.NullReferenceException occurs when their is no data/result
string getValue = cmd.ExecuteScalar().ToString();
if (getValue != null)
{
result = getValue.ToString();
}
conn.Close();
return result;
}
解决方案
There is no need to keep calling .ToString() as getValue is already a string.
Aside that, this line could possibly be your problem:
string getValue = cmd.ExecuteScalar().ToString();
If there are no rows .ExecuteScalar will return null so you need to do some checking.
For instance:
var firstColumn = cmd.ExecuteScalar();
if (firstColumn != null) {
result = firstColumn.ToString();
}