我正在努力解决一个小问题:SqliteDataReader
的转换值转换为 float
.我正在展示我是如何尝试转换的。
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;
你能帮我如何从
reader["actual_price]
获取值吗?进入我的属性(property)ActualPrice
?
最佳答案
我的建议是
首先尝试将列值读取为字符串,例如
Pricing pricing = new Pricing();
string string_val=convert.ToString(reader["actual_price"]);
然后使用 TryParse
如果您的属性是 double 类型,请使用 double.TryParse
float _val=0;
float.Tryparse(string_val,out _val);
然后分配模型属性,如
pricing.ActualPrice =_val;
进行字符串转换然后 Tryparse 的好处是它可以帮助您处理空值异常
可能这也可以通过其他一些更简单的方式来完成
关于c#-4.0 - 如何在 C# 中将 SQLiteDataReader 值转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35597099/