开发者

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 fl开发者_开发知识库oat. 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


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.


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.


Read it is float first:

float value = reader.GetFloat(reader.GetOrdinal("Balance"));

and then ToString() it:

txtbalance.Text = value.ToString();

and if you want you can format it (example with currency format):

txtbalance.Text = value.ToString("C");


Use reader["Balance"].ToString()


Try

 txtbalance.Text= value.toString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜