使用排序将双倍强制填充到2个小数位的DataGridView列 [英] Populate DataGridView Column With a Double forcing to 2 Decimal Places, with Sort
问题描述
对不起,标题怪异,但我不知道该如何用更好的措辞.
Sorry for the weird title but I didn't know how to phrase it any better.
我试图用一个具有2个小数位的数字填充DataGridView上的一列.
I'm trying to populate a column on my DataGridView with a number that has 2 decimal places.
为此,我正在使用
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.
我在网上发现,如果将输入的数据转换为数字类型(双精度,整数等),它将像数字而不是字符串那样对它进行排序. 效果很好,但是将任何具有2个小数位(即1.00)的整数的值都更改为0个小数位.
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
然后我将其格式化为小数点后2位
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
有什么方法可以将这些值格式化为小数点后两位,但保留双精度类型以使列正确排序来填充DataGridView?
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.
任何帮助将不胜感激
推荐答案
您正在使用旧版VB格式功能将值转换为字符串:
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
转换后,其他小数位将丢失.使用DefaultCellStyle
的Format
属性对该列指定所需的小数位数(N2
表示2个小数).与VB的Format
不同,它的作用类似于"DisplayAs",而无需更改值或更改Type.
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
"以启动列编辑器 - 选择该列
- 点击
DefaultCellStyle
属性 - 对于
Format
,单击...
按钮以从列表中进行选择.Numeric
和2 Decimals
产生N2
- In the Properties pane, select
Columns
to start the column editor - Pick the column
- Click the
DefaultCellStyle
property - For
Format
, click the...
button to select from a list.Numeric
and2 Decimals
results inN2
如果在该列中存储数字值,则只会显示2个小数位,但实际/原始值仍然可用,并且排序将使用数字值而不是文本排序.
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.
这篇关于使用排序将双倍强制填充到2个小数位的DataGridView列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!