andrew67
asked on
Object cannot be cast from DBNull to other types.
hi all im running the following code in a web page that is calling a stored procedure to get the max value from a field
cmd.CommandType = CommandType.StoredProcedur e;
cmd.Parameters.Add("@menuS ubjectId", SqlDbType. Int,4).Val ue = Request.Form["sectionId"]. ToString() ;
con.Open();
SqlDataReader srdr = cmd.ExecuteReader(System.D ata.Comman dBehavior. CloseConne ction);
//int results = 0;
while(srdr.Read())
{
results = Convert.ToInt32(srdr[0]);
}
con.Close();
}
all runs well until there is no value in the table for this particular section then i get the following error
Object cannot be cast from DBNull to other types.
if tried putting
if(srdr[0] == null) around it but its just the same
any clues
thanks
cmd.CommandType = CommandType.StoredProcedur
cmd.Parameters.Add("@menuS
con.Open();
SqlDataReader srdr = cmd.ExecuteReader(System.D
//int results = 0;
while(srdr.Read())
{
results = Convert.ToInt32(srdr[0]);
}
con.Close();
}
all runs well until there is no value in the table for this particular section then i get the following error
Object cannot be cast from DBNull to other types.
if tried putting
if(srdr[0] == null) around it but its just the same
any clues
thanks
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
mega thanks
cmd.CommandType = CommandType.StoredProcedur
cmd.Parameters.Add("@menuS
con.Open();
SqlDataReader srdr = cmd.ExecuteReader(System.D
//int results = 0;
while(srdr.Read())
{
results = ConvertToInt32(srdr[0]);
}
con.Close();
}
private Int32 ConvertToInt32(object value)
{
if (IsDBNull(value))
{
return 0;
}
else
{
return (Convert.ToInt32(value));
}
}