c# - Return value using String result=Command.ExecuteScalar() error occurs when result returns null -
i want fetch 1st row 1st cell value database works below code . when there no result found throws exception.
how handle dbnull .
should change query ? return value if theirs no record ?
system.nullreferenceexception: object reference not set instance of object.
code:
public string absentdayno(datetime sdate, datetime edate, string idemp) { string result="0"; string myquery="select count(idemp_atd) absentdayno td_atd "; myquery +=" absentdate_atd between '"+sdate+"' , '"+edate+" "; myquery +=" , idemp_atd='"+idemp+"' group idemp_atd "; sqlcommand cmd = new sqlcommand(myquery, conn); conn.open(); //system.nullreferenceexception occurs when no data/result string getvalue = cmd.executescalar().tostring(); if (getvalue != null) { result = getvalue.tostring(); } conn.close(); return result; }
there no need keep calling .tostring() getvalue string.
aside that, line possibly problem:
string getvalue = cmd.executescalar().tostring(); if there no rows .executescalar return null need checking.
for instance:
var firstcolumn = cmd.executescalar(); if (firstcolumn != null) { result = firstcolumn.tostring(); }
Comments
Post a Comment