2015-04-06 99 views
-2

我得到一个错误“对象不能从DBNull转换到其他类型的”请帮助我,我是新来这个对象不能从DBNull转换到其他类型的

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(); 
     } 
+0

相关:http://stackoverflow.com/questions/6098646/object-cannot-be-cast-from-dbnull-to-other-types – 2015-04-06 07:12:45

+0

尝试谷歌的错误,而不是发布,这是一个很常见错误和大量的帖子关​​于它 – Shubhojit 2015-04-06 07:14:34

+0

我试过搜索。但它没有工作..你能帮我解决这个问题吗? – Career 2015-04-06 07:19:45

回答

1

我相信你有一个空值在你桌子的那个位置。在尝试转换它之前,请确保它不为空。

if(!Convert.IsDBNull(dr[4])) 
{ 
count = Convert.ToInt16(dr[4]); 
//whatever you need done with the count in here... 
} 
相关问题