Set DataFormatString to DataGridView at runtime?

Is it possible to set the DataFormatString property of a column or cell in an ASP.NET DataGridView at run time?

+3
source share
3 answers

There seems to be no way to set the DataFormatString property. I finished binding the data source to the table, and then looked at all the cells and formatted them manually:

DataGridView.AutoGenerateColumns = true;
DataGridView.DataSource = dbconnection.getDataReader();
DataGridView.DataBind();

int result;

for (int i = 0; i < DataGridView.Rows.Count; i++)
{
  foreach (TableCell c in DataGridView.Rows[i].Cells)
  {
    if (int.TryParse(c.Text, out result))
    {
      c.Text = String.Format("{0:n0}", result);
    }
  }
}

This method works great for me. Not sure how this will expand with a large dataset, although I assume that everything will be fine.

+1
source

That should work.

BoundField priceField = grid.Columns[0] as BoundField;
priceField.DataFormatString = "{0:c}";
priceField.HtmlEncode = false;
grid.DataSource = list;
grid.DataBind();

Found through http://geekswithblogs.net/michelotti/archive/2006/03/30/73896.aspx

+2

I don't know what I know, you might want to try formatting the column formatting in the RowDataBound event, although it may have some performance. We will be glad if someone can offer a simpler method.

+1
source

Source: https://habr.com/ru/post/1715091/


All Articles