Search code examples
c#formsdatagridviewdecimalformatnumericupdown

How to Increase or Decrease decimal places in datagridview cells using a NumericUpDown control?


Basically I have a datagridview, some rows contain text and the other rows contain decimal with roughly 7 decimal points, and I would like to use NumericUpDown control to reduce or increase the decimal of cells that have a numerical value.

i tried to use a method with the following line but it didn't work.

this.DatagridviewDinamic.Columns.Items[i].DefaultCellStyle.Format = "0.00##";

Solution

  • You can use the standard format specifiers "N" and "F" instead of that custom format specifier. I often get them mixed up but I believe that "N" will include group separators (e.g. 12,345) and "F" will not (e.g. 12345). You can specify the number of decimal places, e.g. "N2" or "F2" to force two decimal places, so you can do something like this:

    this.DatagridviewDinamic.Columns[i].DefaultCellStyle.Format = $"F{myNumericUpDown.Value}";
    

    If you want it to change with the NumericUpDown, you'll obviously need to handle the ValueChanged event and execute that code in the handler.

    I'm not 100% sure that changing the DefaultCellStyle will affect cells already in the column. If it doesn't, you may have to loop through the cells in the column and make the same change to their Style properties.