问题描述:

i have a datagridview that i have populated programmatically and i was wondering how i can make one of the columns conform to a specified format - "C2".

Can this be done after the datasource has been assigned?

Cheers.

网友答案:
       var persons = new[] {new {name = "aaa", salary = 40000}, 
                     new  {name = "aaa", salary = 40000}, 
                     new  {name = "aaa", salary = 40000}, 
                     new  {name = "aaa", salary = 40000}};


    GridView1.DataSource = persons;
    GridView1.AutoGenerateColumns = false;

    var NameField = new BoundField();

    NameField.HeaderText = "Name";
    NameField.DataField = "name";
    GridView1.Columns.Add(NameField);

    var SalaryField = new BoundField();
    SalaryField.HeaderText = "Salary";
    SalaryField.DataField = "salary";
    SalaryField.DataFormatString = "{0:c2}";
    SalaryField.HtmlEncode = false;
    GridView1.Columns.Add(SalaryField);


    GridView1.DataBind();
网友答案:

You can also do it in grid_ColumnAdded event handler like that.

  if (e.Column.HeaderText == "YourColumnHeaderText") 
    {
     e.Column.DefaultCellStyle.Format = "C2";
    }
网友答案:

Rob's answer is for a GridView (web control) not a DataGridView (winforms control).

I've adapted his answer for winforms.

var persons = new[] {new {name = "aaa", salary = 40000}, 
                 new  {name = "aaa", salary = 40000}, 
                 new  {name = "aaa", salary = 40000}, 
                 new  {name = "aaa", salary = 40000}};

DataGridView1.AutoGenerateColumns = false;

var NameField = new DataGridTextBoxColumn();

NameField.HeaderText = "Name";
NameField.DataPropertyName = "name";
DataGridView1.Columns.Add(NameField);

var SalaryField = new DataGridViewTextBoxColumn();
SalaryField.HeaderText = "Salary";
SalaryField.DataPropertyName = "salary";
SalaryField.DefaultCellStyle.Format = "{0:c2}";
DataGridView1.Columns.Add(SalaryField);

DataGridView1.DataSource = persons;

Things to note:

  1. The DataSource is set at the end of the column definitions - this is because a DataGridView will auto data bind when it's data is set.
  2. The columns are set to DataGridViewTextBoxColumns. This is the standard way to show text information in a DataGridView. If you use DataGridViewColumn then it won't know how to display the data.
相关阅读:
Top