0

I have a problem about Datagridview cell formatting. I'm adding my example codes below,i tried many percentage formats about this but it is not working anymore. Where is the problem, can you help me?

private void button1_Click(object sender, EventArgs e)
{
        DataTable tb = new DataTable();
        DataRow row = tb.NewRow();
        tb.Rows.Add(row);
        tb.Columns.Add("Column1");
        tb.Rows[0][0] = "45";

        dataGridView1.DataSource = tb;
        dataGridView1.Columns[0].DefaultCellStyle.Format = "#.000\\%";
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
fthgrsy
  • 13
  • 1
  • 5
  • 1
    What do you mean by _not working_ exactly? You get error or exception? Unexpected result? If so, what result do you want? – Soner Gönül Feb 25 '16 at 10:53
  • i want to display this value 45%, but nothing happens, no error or exception, cell value is 45, not 45% – fthgrsy Feb 25 '16 at 12:49

1 Answers1

0

Because both "0" and "#" specifiers are custom numeric format strings. Since your "45" is string, there will be no formatting at all.

As a solution, supply your first column values as a numeric like;

tb.Rows[0][0] = 45;

after that, divide your all first column values by 100.0 as a floating point division (you get 0.45 for example),

foreach (DataRow row in tb.Rows)
{
   row[0] = (int)row[0] / 100.0;
}

and use The "%" Custom Specifier to format it like;

dataGridView1.Columns[0].DefaultCellStyle.Format = "#%";

This % specifier multiples your value by 100 and % symbol after it if your CurrentCulture already has % as a PercentSymbol.

For example;

Console.WriteLine((0.45).ToString("#%")); // prints 45%
Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364