C#中Datagridview的数字格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18299040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Number Format For Datagridview in C#
提问by ROM
I want to set the datagridview values in number format. Currently I am getting this:
我想以数字格式设置 datagridview 值。目前我得到这个:
I want something like this:
我想要这样的东西:
I have used this code:
我用过这个代码:
dgvmain.DefaultCellStyle.Format = "#.##0";
And this code
而这段代码
dgvmain.Columns["Amount"].DefaultCellStyle.Format = "#.##0";
But neither of this working.
但这都不起作用。
回答by Muneeb Mirza
Goto your Form's Design mode then goto the properties of dgvmain there check DefaultCellStyle and set the format as you like.
转到表单的设计模式,然后转到 dgvmain 的属性,检查 DefaultCellStyle 并根据需要设置格式。
OR
或者
you can do this
你可以这样做
dgvmain.Columns["Amount"].DefaultCellStyle.Format = "N2";
dgvmain.Columns["Amount"].DefaultCellStyle.Format = "N2";
:)
:)
回答by abhishek
You can Set you Format String using CellStyle Builder an set the Custom format to # mm
您可以使用 CellStyle Builder 设置格式字符串并将自定义格式设置为 # mm
How to do it :
怎么做 :
- Right click on Grid, then Properties
- In the property window, click the button that will popup up the Edit Columns Dialog
- Select the cell you want to format
- On the right side of the Edit Columns Dialog select the DefaultCellStyle property Click the DefaultCellStyle property, then the CellStyleBuilder dialog will open Here you have the format property, this will give you the Format String Dialog
- Set the Custom property to N2 you will see the preview at the bottom
- Click OK ... till you are back to your Grid...
- 右键单击网格,然后单击属性
- 在属性窗口中,单击将弹出编辑列对话框的按钮
- 选择要格式化的单元格
- 在 Edit Columns 对话框的右侧选择 DefaultCellStyle 属性 单击 DefaultCellStyle 属性,然后 CellStyleBuilder 对话框将打开 这里您有格式属性,这将为您提供格式字符串对话框
- 将自定义属性设置为 N2,您将在底部看到预览
- 单击确定...直到您返回网格...
If you want to do it from Code, put this code inside Form_load event.
如果您想从代码中执行此操作,请将此代码放入 Form_load 事件中。
dgvmain.Columns["Amount"].DefaultCellStyle.Format = "N2";
回答by CLS
You have to spot, that all the data on your first screenshot are left aligned.
您必须发现,第一个屏幕截图上的所有数据都是左对齐的。
The formatting you try, and the others adviced are good. I must note, DefaultCellStyle most be used beforeyou add columns to the grid. The case, that it seems specified formats does not work, tells me your data type may be string, not numeric.
您尝试的格式以及其他建议的格式都很好。我必须注意,在向网格添加列之前最常使用 DefaultCellStyle 。似乎指定格式不起作用的情况告诉我您的数据类型可能是 string 而不是 numeric。
回答by eiji
Try
尝试
dgvmain.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;