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

LVL 3
andrew67Asked:
Who is Participating?
 
MogalManicConnect With a Mentor Commented:
srdr[0] is not equal to Null but DBNull.  Put the following test inside the while loop:

if (srdr[0] is DBNull)
  results=-1;  //Or whatever you define NULL results as
else
  results = Convert.ToInt32(srdr[0]);

Open in new window

0
 
balochdudeCommented:
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));
        }
    }
0
 
andrew67Author Commented:
mega thanks
0
All Courses

From novice to tech pro — start learning today.