[英]System.InvalidCastException: Specified cast is not valid in C# using postgres datareader
I am trying to pull data from database using postgre in C# and putting the values returned in label controls. 我试图在C#中使用postgre从数据库中提取数据,并将返回的值放在标签控件中。 I keep getting System.InvalidCasaeExeception.
我一直在获取System.InvalidCasaeExeception。 The database field is an integer so I a using a data reader to get the value.
数据库字段是整数,因此我使用数据读取器来获取值。
here is my code 这是我的代码
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();
}
}
}
Not sure why it wont work. 不知道为什么它不起作用。 I pulled the first element and it displays correctly.
我拉了第一个元素,它显示正确。 some of the data is integers but have null values in the DB.
一些数据是整数,但数据库中的值为空。 I tried an element with data but I get the cast exception error.
我尝试了带有数据的元素,但出现强制转换异常错误。 Please help.
请帮忙。
I got it working, thank you all for you help and tips!! 我成功了,谢谢大家的帮助和提示!!
here is a snippit of the working code 这是工作代码的摘要
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();
You should check that the value is not null. 您应该检查该值是否不为null。 Try the following instead:
请尝试以下操作:
lblCrookedPart.Text = (dr.IsDBNull(12)) ? "NULL" : dr.GetInt32(12).ToString();
Try something like this 试试这个
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.