Search code examples
c#asp.netdatagridviewdataformat

Set DataFormatString on DataGridView at Runtime?


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


Solution

  • There doesn't seem to be a way to set the DataFormatString property. I have ended up binding the datasource to the table and then going through all the cells and formatting 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 perfectly for me. Not sure how it would scale up with a large dataset although my guess is it would be fine.