C# – DataGridView Format Decimal Values with AutoGenerateColumns

cdatagridviewdecimal-pointwinforms

I have a datagridview that uses AutoGenerateColumns in winforms. There is a date column and then 1-16 data columns containing numeric values. I want all of these 1-16 data columns to be formatted to 4 decimal places.

As per this post, you set the DefaultCellStyle through the designer. I did this manually to get what format that I want to use. I set this in the form constructor:

this.dgv_PreviewGrid.DefaultCellStyle.Format = "N4";

I have tried setting it this way and also tried manually on each column on DataBindingComplete event. Nothing happens! The app lags as though it is doing the rounding, but doesn't.

Also, is there a link to msdn or something with a list of the DefaultCellStyle formats? Couldn't find them.

EDIT: I found that using Format "D4" instead of "N4" (Decimal vs. Number) –> is probably the format that I want, but it is still not working.

Best Answer

The MSDN page you want is Standard Numeric Format Strings.

You want the N or F format specifier, not D. D is for integers.

Setting grid.DefaultCellStyle.Format should work, but since you have a date column you will need to override that column's DefaultCellStyle, or the dates won't display.

What is the actual type of the numeric property on your datasource? Are you sure it isn't a string? How are you populating the DataGridView?

Without more information it's difficult to guess the problem. It might help if you show the code that populates the DataGridView.