0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

hello, thank you for your answer, is there way to improve the read command? Thank you for your time.
If you can further explain what you mean with "improve the read command", I may can help out.
I mean this line of code: textBox19.Text = precti.GetDecimal(22).ToString().Replace(',', '.');
Thank you so much, is there way to make it without the free space? now it is like 1 123 instead of 1123
change the n to d, n will result to being formatted like the culture says so when the thousand splitter is a dot it would be - 1.123 with d you are ignoring this and and just display a regular number without the format. so: textBox19.Text = string.Format("{0:d0}", precti.GetDecimal(22)); a nice little page about format is here: alexonasp.net/samples/stringformatting
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.