SqlDataReader 显示 InvalidCastException(C# Windows 窗体)
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString);
sqlConn.Open();
SqlCommand sqlComm = new SqlCommand("SELECT Price FROM Pricing WHERE FoodID = 1", sqlConn);
SqlDataReader r = sqlComm.ExecuteReader();
while (r.Read())
{
price1 = (float)r["Price"];
}
r.Close();
sqlConn.Close();
我得到的 InvalidCastException 错误指向“price1 = (float)r["Price"];”我是 C# 和任何编程语言的新手,请指导我!
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString);
sqlConn.Open();
SqlCommand sqlComm = new SqlCommand("SELECT Price FROM Pricing WHERE FoodID = 1", sqlConn);
SqlDataReader r = sqlComm.ExecuteReader();
while (r.Read())
{
price1 = (float)r["Price"];
}
r.Close();
sqlConn.Close();
The InvalidCastException error i get points to "price1 = (float)r["Price"];" im new to c# and any of the programming languages , please guide me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设价格是浮点数,您应该使用 GetFloat< /a> 相反:
Assuming Price is a float, you should use GetFloat instead:
您可以以更安全的方式重写代码,如下所示:
这样您就可以确定,无论发生什么情况,阅读器和连接都将关闭并为您处理。如果您调试此代码,您将看到运行时将在 Price1 变量中存储哪种类型的对象,然后您可以在需要时转换为该类型,因为如果您转换为 float 失败,我认为您没有得到正确地从读卡器上浮动。
SqlDataReader 还有其他方法来检索数据,如果您确定 Price 是一个 fload,则可以使用 reader.GetSingle 方法,例如,如果它是 int,则可以使用 reader.GetInt等等。
you can rewrite your code in a much safer way, like this:
so you are sure that no matter what happens reader and connection will be closed and disposed for you. if you debug this code you will see what kind of object will be stored in the price1 variable at runtime and you can then cast to that type afterwards, if needed, because if your cast to float was failing, I thing you were not getting the float properly from the reader.
The SqlDataReader has also other methods to retrieve data, if you are sure that Price is a fload you can use
reader.GetSingle
method for example, if it was an int you could usereader.GetInt
and so on.这意味着您的“价格”列不是浮点值 - 如果您像这样进行转换,则类型必须完全正确,您可以尝试更宽松的方法,将其转换为浮点值:
如果“price”列包含不同的数据类型(这很可能),则应使用本机类型并将变量设置为该类型,即如果它是
double
makeprice1< /code> 一个
double
变量代替:This means that your "price" column is not a float value - if you cast like this, the type has to be exactly right, you can try the more lenient way by converting it to a float value:
If the "price" column contains a different data type (which is very likely), you should use the native type instead and make your variable that type, i.e. if its a
double
makeprice1
adouble
variable instead: