如何在c#中将SQLiteDataReader值转换为float

时间:2016-02-24 08:38:06

标签: c#-4.0 casting sqlite floating-point

我正在努力解决一个小问题:将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]获取我的财产ActualPrice中的值?

1 个答案:

答案 0 :(得分:1)

我的建议是

首先尝试将列值读取为

之类的字符串
   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会帮助你处理空值异常

这可以通过其他一些更简单的方式来完成