Set DataFormatString on DataGridView at Runtime?

只谈情不闲聊 提交于 2019-12-14 01:19:40

问题


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


回答1:


This should work.

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

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




回答2:


Not that I know of, you might want to try peforming the column formatting on RowDataBound event though might have some performance degrade. Will be glad if someone can provide a simpler method.




回答3:


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.



来源:https://stackoverflow.com/questions/1272771/set-dataformatstring-on-datagridview-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!