我收到错误“对象无法从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 :(得分:1)
我相信你表中的那个位置有一个空值。在尝试转换它之前,请确保它不为空。
if(!Convert.IsDBNull(dr[4]))
{
count = Convert.ToInt16(dr[4]);
//whatever you need done with the count in here...
}