Unable to cast object of type 'System.Double' to type 'System.String'
Solution 1
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.
Solution 2
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.
Solution 3
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");
Solution 4
Use reader["Balance"].ToString()
Nubkadiya
Updated on January 17, 2020Comments
-
Nubkadiya over 4 years
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 isfloat
. 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
-
HABJAN over 13 yearsDont you see that "valu" variable is declared as String ?
-
Saeed Amiri over 13 years@HABJAN, I'd answer in editor, and forgot about it, fixed it.