Reputation: 1867
I am struggling with a small issue: conversion of SqliteDataReader
values into float
. I am demonstrating how I am trying to cast.
Pricing pricing = null;
SQLiteConnection con = new SQLiteConnection(thisApp.dbConnectionString);
try
{
string _sql = "select * from pricing where id=@id";
SQLiteCommand command = new SQLiteCommand(_sql, con);
command.Parameters.AddWithValue("id", myid);
con.Open();
SQLiteDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
pricing = new Pricing()
{
// "ActualPrice" in my model and "actual_price" in sqlite db are Float type.
// But here i am getting error saying cast is not allowed
// It tried one more way as well but didn't work.
ActualPrice = Convert.ToInt32(reader["actual_price"])
// OR
ActualPrice = (float) Convert.ToInt32(reader["actual_price"])
};
}
}
}
catch
{
}
finally
{
if (con.State != ConnectionState.Closed)
con.Close();
}
return pricing;
Can you help me how can I get values from reader["actual_price]
into my property ActualPrice
?
Upvotes: 1
Views: 562
Reputation: 4811
My suggestion is
First try to read the column value as a string like
Pricing pricing = new Pricing();
string string_val=convert.ToString(reader["actual_price"]);
Then use a TryParse
If your property is of type double use double.TryParse
float _val=0;
float.Tryparse(string_val,out _val);
Then assign model property like
pricing.ActualPrice =_val;
The benefit of doing string conversion & then Tryparse is it will helps you to handle null value exceptions
Might be this can be done in some other simpler ways as well
Upvotes: 1