-2

I am getting an error "Object cannot be cast from DBNull to other types" Please help me i am new to this

public void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
   int count = 0;
        SqlConnection con = new SqlConnection("server=ADMIN- PC\\SQLEXPRESS;initial catalog=content;integrated security=true");
        con.Open();
        SqlCommand cmd;
        cmd = new SqlCommand("select * from usrimg where ImageName='" + GridView1.SelectedDataKey["ImageName"].ToString() + "'", con);
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {

            count = Convert.ToInt16(dr[4]);//Error:Object cannot be cast from DBNull to other types 
            count++;
            dr.Close();
            cmd = new SqlCommand("update usrimg set [count] =" + count + "where ImageName='" + GridView1.SelectedDataKey["Image Name"].ToString() + ")", con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
bit
  • 4,407
  • 1
  • 28
  • 50
Career
  • 13
  • 4

1 Answers1

1

I believe you have a null value in that position in your table. Try making sure it's not null before you try to convert it.

if(!Convert.IsDBNull(dr[4]))
{
count = Convert.ToInt16(dr[4]);
//whatever you need done with the count in here...
}
Wendy E
  • 99
  • 4