SqlDataReader showing me InvalidCastException(C# Windows Form)
SqlConnection sqlConn = new SqlConnection开发者_如何学Python(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!
Assuming Price is a float, you should use GetFloat instead:
price1 = r.GetFloat(0); // first column
you can rewrite your code in a much safer way, like this:
using(var sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["myDB"].ConnectionString))
{
sqlConn.Open();
SqlCommand sqlComm = new SqlCommand("SELECT Price FROM Pricing WHERE FoodID = 1", sqlConn);
using(var reader = sqlComm.ExecuteReader())
{
while (reader.Read())
{
var price1 = reader["Price"];
}
}
}
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 use reader.GetInt
and so on.
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:
price1 = Convert.ToSingle(r["Price"]);
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
make price1
a double
variable instead:
price1 = reader.GetDouble(0);
精彩评论