Formatting datagridview cell to 2 decimal places
Asked Answered
A

5

7

Basically I have a datagridview which displays data from a datatable. Each cell in the datatable is a decimal with roughly 10 decimal points, how can I use the datagridview to display this data to 2 decimal points?

I have tried this (what I found in other questions):

        for (int i = 0; i < this.dgvDynamics1.Columns.Count; i++)
            this.dgvDynamics1.Columns[i].DefaultCellStyle.Format = "N2";

but it doesn't work

If you need any more info let me know

Thanks in advance

Akan answered 13/8, 2014 at 8:26 Comment(1)
This may help you on your wayBaroscope
C
9

Try this:

this.dgvDynamics1.Columns.Items[i].DefaultCellStyle.Format = "0.00##";
this.dgvDynamics1.Columns.Items[i].ValueType = GetType(Double)
Coastwise answered 13/8, 2014 at 8:43 Comment(5)
That seems to be the answer for everyone else but it doesn't work for meAkan
I think it would be more helpful for the OP and further visitors, when you add some explaination to your intension.Spendthrift
no difference, I am going to try and use the formatting event handlerAkan
Try Adding Items[] above - not sure if you can get columns by indexCoastwise
I was able to make this work, without the second line in the example.Santa
D
9

try this

private void dgvList_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 6 || e.ColumnIndex == 8)
        {
            e.CellStyle.Format = "N2";
        }
    }
Deirdra answered 10/8, 2017 at 3:55 Comment(0)
B
0

This is an old post, but for the record, this should work:

for (int i = 0; i < this.dgvDynamics1.Columns.Count; i++)
    this.dgvDynamics1.Columns[i].DefaultCellStyle.Format = "0.00";
Brittaneybrittani answered 11/5, 2020 at 20:10 Comment(0)
B
0

Personally, I always change the format in the designer with no problems. Here's how:

Here the procedure

Bureaucrat answered 29/7, 2022 at 6:1 Comment(0)
F
0

Try this code :

 foreach(DataGridViewColumn column in dgvDynamics1.Columns)
   {
  column.DefaultCellStyle.Format = "N2";
   }

if you need specific columns you can use :

this.dgvDynamics1.Columns[YourCoulmnIndex].DefaultCellStyle.Format = "N2";
Fuqua answered 15/11, 2023 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.