2015-04-06 52 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... 
} 
相關問題