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!
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.GetSinglemethod for example, if it was an int you could usereader.GetIntand so on.