bolt19
bolt19

Reputation: 2053

Formatting datagridview cell to 2 decimal places

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

Upvotes: 7

Views: 39100

Answers (5)

adnan Alyaari
adnan Alyaari

Reputation: 61

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";

Upvotes: 0

Hytac
Hytac

Reputation: 206

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

Here the procedure

Upvotes: 0

Felipe
Felipe

Reputation: 29

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";

Upvotes: 0

Michael azzar
Michael azzar

Reputation: 321

try this

private void dgvList_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 6 || e.ColumnIndex == 8)
        {
            e.CellStyle.Format = "N2";
        }
    }

Upvotes: 9

reach4thelasers
reach4thelasers

Reputation: 26919

Try this:

this.dgvDynamics1.Columns.Items[i].DefaultCellStyle.Format = "0.00##";
this.dgvDynamics1.Columns.Items[i].ValueType = GetType(Double)

Upvotes: 9

Related Questions