c#, Set datagridview column format after datasource has been set

11,331

Solution 1

       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();

Solution 2

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.

Solution 3

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

  if (e.Column.HeaderText == "YourColumnHeaderText") 
    {
     e.Column.DefaultCellStyle.Format = "C2";
    }
Share:
11,331
Grant
Author by

Grant

Updated on June 08, 2022

Comments

  • Grant
    Grant almost 2 years

    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.