【问题标题】:Object cannot be cast from DBNull to other types [duplicate]对象不能从 DBNull 转换为其他类型 [重复]
【发布时间】:2015-04-06 07:09:10
【问题描述】:

我收到一个错误“无法将对象从 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();
        }

【问题讨论】:

  • 尝试谷歌错误而不是发布,这是一个非常常见的错误并且有很多关于它的帖子
  • 我试过搜索。但它没有用..你能帮我解决这个问题吗

标签: c# sql asp.net sql-server-2008


【解决方案1】:

我相信您在表格中的那个位置有一个空值。在尝试转换之前尝试确保它不为空。

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

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多