Number Format For Datagridview in C#

泄露秘密 提交于 2020-01-10 05:26:46

问题


I want to set the datagridview values in number format. Currently I am getting this:

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.


回答1:


You can Set you Format String using CellStyle Builder an set the Custom format to # mm

How to do it :

  1. Right click on Grid, then Properties
  2. In the property window, click the button that will popup up the Edit Columns Dialog
  3. Select the cell you want to format
  4. 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
  5. Set the Custom property to N2 you will see the preview at the bottom
  6. Click OK ... till you are back to your Grid...

If you want to do it from Code, put this code inside Form_load event.

dgvmain.Columns["Amount"].DefaultCellStyle.Format = "N2";



回答2:


Goto your Form's Design mode then goto the properties of dgvmain there check DefaultCellStyle and set the format as you like.

OR

you can do this

dgvmain.Columns["Amount"].DefaultCellStyle.Format = "N2";

:)




回答3:


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 before you 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.




回答4:


Try

dgvmain.Columns["Amount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;


来源:https://stackoverflow.com/questions/18299040/number-format-for-datagridview-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!