簡體   English   中英

System.InvalidCastException:使用postgres datareader在C#中指定的強制轉換無效

[英]System.InvalidCastException: Specified cast is not valid in C# using postgres datareader

我試圖在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();
        }
    }

}

不知道為什么它不起作用。 我拉了第一個元素,它顯示正確。 一些數據是整數,但數據庫中的值為空。 我嘗試了帶有數據的元素,但出現強制轉換異常錯誤。 請幫忙。

我成功了,謝謝大家的幫助和提示!!

這是工作代碼的摘要

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();

您應該檢查該值是否不為null。 請嘗試以下操作:

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

試試這個

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM