error Object cannot be cast from DBNull to other types.problem how to solve
hi guys have problem
firstly code
function maxtotalquantity
public int maxtotalquantity(string connectionstring)
{
sqlconnection con = new sqlconnection(connectionstring);
sqlcommand cmd = new sqlcommand();
cmd.connection = con;
cmd.commandtype = commandtype.text;
cmd.commandtext = "select max(totalquantity) dbo.endwork";
con.open();
int commit = convert.toint32(cmd.executescalar());
con.close();
return commit;
}
calling function
sales.salesclass salesclass4 = new sales.salesclass();
int totalquantity = salesclass4.maxtotalquantity("data source=192.168.1.3;initial catalog=yamo;user id=admin;password=2233;connection lifetime=3;max pool size=3;connection timeout=30");
label10.text = totalquantity.tostring();
end work table
id int unchecked
qunatityend int checked
position nvarchar(50) checked
issentint checked
totalquantity int checked
unchecked
but error show me when run code give me
error object cannot cast dbnull other types.
some times value found in totalquantity null
what need convert null 0 when null found show 0 , exception not show
how solve problem
exception error show in lineint commit = convert.toint32(cmd.executescalar());
how solve
a database query such might return database null, have check manually.
object val = cmd.executescalar(); if (val == null || val = dbnull.value) { commit = 0; } else { commit = (int) val; }can bit long-winded if need multiple times of course, quite easy wrap in little utility method such rein's answer in link
Visual Studio Languages , .NET Framework > Visual C#
Comments
Post a Comment