System.InvalidCastException:使用postgres datareader在C#中指定的强制转换无效

时间:2014-12-16 20:13:03

标签: c# postgresql

我正在尝试使用C#中的postgre从数据库中提取数据,并将标签控件中返回的值放入。我一直在收到System.InvalidCasaeExeception。数据库字段是一个整数,所以我使用数据读取器来获取值。

这是我的代码

private void Get_Defects()
    {
        NpgsqlConnection conn = Connection.getConnection();

        try
        {
            conn.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("select * from defect where defect_id >= :MinID and defect_id <= :MaxID and location_id = 102 and top_or_bottom = :TopBottom;", conn);
            cmd.Parameters.Add(new NpgsqlParameter("MinID", MinID));
            cmd.Parameters.Add(new NpgsqlParameter("MaxID", MaxID));
            cmd.Parameters.Add(new NpgsqlParameter("TopBottom", TopBottom));

            NpgsqlDataReader dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                lblCrookedPart.Text = dr.GetInt32(12).ToString();
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {
            conn.Close();
        }
    }

}

不确定为什么它不会工作。我拉了第一个元素,它显示正确。一些数据是整数但在DB中具有空值。我尝试了一个带数据的元素,但是我得到了强制转换异常错误。请帮忙。

3 个答案:

答案 0 :(得分:1)

我得到了它的工作,谢谢大家的帮助和提示!!

这是工作代码的信息

conn.Open();
            NpgsqlDataAdapter da = new NpgsqlDataAdapter("select * from defect where defect_id >= '"+MinID+"' and defect_id <= '"+MaxID+"' and location_id = 102 and top_or_bottom = '"+TopBottom+"';", conn);
            ds.Reset();
            da.Fill(ds);
            dt = ds.Tables[0];

            //Used to sum the column values

            object CrookedPartTotal = dt.Compute("Sum(crooked_part)", "defect_id >= '" + MinID + "' and defect_id <= '" + MaxID + "'");
            if (CrookedPartTotal.ToString() == "")
                lblCrookedPart.Text = "0";
            else
                lblCrookedPart.Text = CrookedPartTotal.ToString();


            object TooMuchSolder = dt.Compute("Sum(too_much_solder)", "defect_id >= '" + MinID + "' and defect_id <= '" + MaxID + "'");
            if (TooMuchSolder.ToString() == "")
                lblTooMuchSolder.Text = "0";
            else
                lblTooMuchSolder.Text = TooMuchSolder.ToString();

答案 1 :(得分:0)

您应该检查该值是否为空。请尝试以下方法:

lblCrookedPart.Text = (dr.IsDBNull(12)) ? "NULL" : dr.GetInt32(12).ToString();

答案 2 :(得分:0)

尝试这样的事情

NpgsqlDataReader da = default(NpgsqlDataReader);
NpgsqlCommand cmd = new NpgsqlCommand("select * from myTable", GenConnection);
string strVAL = null;
da = cmd.ExecuteReader;
if (da.HasRows) {
    while (da.Read) {
        strVAL = (Information.IsDBNull(da["field"]) ? 0 : da["field"]).ToString;
    }
}