Link to home
Start Free TrialLog in
Avatar of andrew67
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.StoredProcedure;
            cmd.Parameters.Add("@menuSubjectId",SqlDbType.Int,4).Value = Request.Form["sectionId"].ToString();
            con.Open();
              SqlDataReader srdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            //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
Avatar of MogalManic
MogalManic
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
roughly something like that:

 cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@menuSubjectId",SqlDbType.Int,4).Value = Request.Form["sectionId"].ToString();
            con.Open();
              SqlDataReader srdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
            //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));
        }
    }
Avatar of andrew67
andrew67

ASKER

mega thanks