Reputation: 107
Sorry for the weird title but I didn't know how to phrase it any better.
I'm trying to populate a column on my DataGridView with a number that has 2 decimal places.
To do this I'm using
Dim _Size as Double = 1.2345
DataGridView1.Item(0, 0).Value = Format(_Size, "0.00")
This populates the data correctly, but when sorting by this column, it treats the item as a string.
I found on the net, that if you convert the data being entered to a number type (double, integer etc..), it will then sort it like a number instead of a string. This works brilliantly, but any values that are integers with 2 decimal places (i.e. 1.00) are changed to 0 decimal places.
So, if I had the following values
1.2345
2.2345
3.2345
4.2345
5.0011
and I formatted as 2 decimal places they would then become
1.23
2.23
3.23
4.23
5.00
if I then converted them back to doubles they then become
1.23
2.23
3.23
4.23
5
Is there any way of populating a DataGridView with these values formatted as 2 decimal places but keeping the double type so that the column sorts correctly?
I hope I've explained this clearly.
Any help would be greatly appreciated
Upvotes: 1
Views: 1938
Reputation: 38895
You are converting your values to string by using the legacy VB Format function:
Function Format(Expression As Object, Optional Style As String = "") As String
When it is converted, the other decimals are lost. Use the Format
Property of the DefaultCellStyle
for that column to specify the number of decimal places you want (N2
for 2 decimals). Unlike VB's Format
, this acts like a "DisplayAs" without altering the value or changing the Type.
Columns
to start the column editorDefaultCellStyle
propertyFormat
, click the ...
button to select from a list. Numeric
and 2 Decimals
results in N2
If you store a numeric values in that column, only 2 decimal places will display, but the actual/original value will still be available and sorting will using the numeric value rather than a text sort.
Upvotes: 2