Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridViewTextBoxColumn add commas in numeric cell

How can I have my datagrid automatically add commas to a cell to format the numbers. I tried changing the format of the defaultcellstyle to numeric but it didn't help.

I'm looking for it to do something like

user enters 503412.45

The number display changes to 503,412.45

UPDATE: I set the format of the column at design time (through the properties window in VS). It is not databound, users manually add rows. The columns are also created at design time by using the Collections option in the properties window

like image 561
JonF Avatar asked Oct 29 '25 09:10

JonF


2 Answers

Setting DefaultCellStyle.Format to "N2" will do this.

dataGridView1.Columns.Add("foo", "foo");
dataGridView1.Columns[0].DefaultCellStyle.Format = "N2";
dataGridView1.Rows.Add(1234.567); // shows 1,234.57

I can't guess why it's not working for you without more details, so all I can suggest is that you think you've set it but you actually haven't. Are you using databinding? How are you adding the columns? Are they auto generated? Do you set the Format at design time or runtime?

like image 75
Igby Largeman Avatar answered Oct 31 '25 04:10

Igby Largeman


To make the output of your solution independent of the current thread's culture (number decimal separator, number group separator) you have to set the format provider for the column:

CultureInfo ci = CultureInfo.CreateSpecificCulture("en-US");

dataGridView1.Columns[0].ValueType = typeof(decimal);
dataGridView1.Columns[0].DefaultCellStyle.FormatProvider = ci;
dataGridView1.Columns[0].DefaultCellStyle.Format = "N2";

Hope, this helps.

like image 41
Hans Avatar answered Oct 31 '25 04:10

Hans