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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With