Blaze M
Blaze M

Reputation: 150

SqlDataReader GetDecimal without .00

I'm wondering how can I read with my SqlDataReader data type numeric (9,2) without .00. Here is my code for reading it:

SqlCommand comm = new SqlCommand("SELECT * FROM table", conn);
                spojeni.Open();
                SqlDataReader reader = comm .ExecuteReader();
textBox19.Text = reader .GetDecimal(22).ToString().Replace(',', '.');
}

Would you please tell me how should I improve this code to read it without .00?

Upvotes: 0

Views: 3095

Answers (1)

Rand Random
Rand Random

Reputation: 7440

You can cast the value in your SQL Statement:

select *, cast(ColumnName as numeric(9,0)) as Alias from klient where ID_K=1

Edit:

I wouldnt use GetDecimal at all since I dont really like the idea of the overload having only an integer to pick, I personally think its better to read with the given columnnames.

So to fetch the data from the cast column I'd do the following:

decimal value = 0;
decimal.TryParse(Convert.ToString(reader["Alias"]), out value);
textBox19.Text = value.ToString();

This can be easily made into an extension of SqlDataReader like this:

public static decimal GetDecimal(this SqlDataReader reader, string columnName)
{
    decimal value = 0;
    decimal.TryParse(Convert.ToString(reader[columnName]), out value);
    return value;
}

And than just call the following:

textBox19.Text = precti.GetDecimal("Alias").ToString();

Edit 2:

Something just came into my mind that maybe is more to your liking. Insted of doing a cast threw the SQL Statement you could just simply format your decimal numer the way you want it to, with the following code:

textBox19.Text = string.Format("{0:n0}", precti.GetDecimal(22));

"{0:n0}" will result in a numeric value with 0 position after decimal point.

Upvotes: 1

Related Questions