1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

my property dataType is not double its float, so this double.Tryparse will work ? But i try first this solution.
Use float Trypasre [ see edit in answer] . My point is instead of trying direct type conversion Use TryParse

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.