Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.Double' to type 'System.String'

SqlDataReader reader;

String sqlreadcom = "SELECT Balance FROM IncomeGenerator";

using (reader = new SqlCommand(sqlreadcom,sqlCon).ExecuteReader())
{
   if(reader.HasRows)
   {
      while(reader.Read())
      {
         String value = reader.GetString(reader.GetOrdinal("Balance"));
         txtbalance.Text = Convert.ToString(value);
      }
   }
}

My Balance field data type is float. I need to convert it to string.

This is the message I'm getting

Unable to cast object of type 'System.Double' to type 'System.String'

Can someone guide me to make this error free

like image 952
Nubkadiya Avatar asked Feb 02 '26 07:02

Nubkadiya


2 Answers

Try it with

object value = reader.GetValue(reader.GetOrdinal("Balance"));
txtbalance.Text = value.ToString();

If there are many rows to read, you should do the GetOrdinal outside of the loop like

int idxBalance = reader.GetOrdinal("Balance");

and use idxBalance later.

like image 144
Matten Avatar answered Feb 04 '26 21:02

Matten


You should use

double val = reader.GetDouble(reader.GetOrdinal("Balance"));

and convert it simply:

txtbalance.Text = val.ToString();

Edit: When I see your code again(if you change it as bellow):

  while(reader.Read())
  {
     var val = reader.GetDouble(reader.GetOrdinal("Balance"));
     txtbalance.Text = val.ToString();
  }

what's the purpose of UI update in each iteration? user can't see anything in this case, in txtbalance.Text = val.ToString(); You just showing last record value. So instead of fetching n item from DB, in your query do some sort of order and just show first item.

like image 24
Saeed Amiri Avatar answered Feb 04 '26 20:02

Saeed Amiri