Reputation: 478
I know this question has been answered many times before however, I'm convinced the code I have is correct but isn't working correctly.
string total = ds.Tables[0].Rows[0][0].ToString();
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
This code isn't adding the commas into my value like it desire it to.
Can anyone see why?
Upvotes: 2
Views: 946
Reputation: 1608
There are 8 overloads for the Strig.Format method. You are using this specific one: Format(String, Object) in which you pass a String
value as argument of the second parameter. This is because you are using a string variable (total
) to assign the value from the dataset in:
string total = ds.Tables[0].Rows[0][0].ToString();
Besides you are using .ToString()
to retrieve it as a String
.
If you are using SQL Server as data source to your ds
dataset and you are certain about the SQL data type
then you can assign that value directly to a variable with the corresponding C# type
. To put it in a different way, SQL data types are mapped to C# data types.
If you are not sure about the C# data type
of ds.Tables[0].Rows[0][0]
then you could simply do the following:
Object total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
And this way you literally use the Format(String, Object)
overload of String.Format
.
Upvotes: 1
Reputation: 186823
When you put
string total = ds.Tables[0].Rows[0][0].ToString();
it means implicit G
("General") format string
string total = ds.Tables[0].Rows[0][0].ToString("G");
Do not format prematurely:
var total = ds.Tables[0].Rows[0][0]; // Value from table
string test = string.Format("{0:N}", total); // Format total with "N" format string
Upvotes: 6
Reputation: 131712
Your code is trying to format a string. If the DataTable contains a number you can pass the format specifier to ToString()
, eg
var test=ds.Tables[0].Rows[0][0].ToString("N");
Or store the contents in a local variable and use String.Format
:
var total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
If the datatable contains a string though, you'd have to parse it to a numeric type first
Upvotes: 2
Reputation: 485
You have to use the string.Format
with a number type, instead of string. In this case, the variable total
is a string, it must be a number.
Upvotes: 1