C #, Set datagridview column format after setting data source

I have a datagridview that I populated programmatically, and I was wondering how I can make one of the columns fit the given format - "C2".

Can this be done after assigning a data source?

Greetings.

+3
source share
3 answers
       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();
+3
source

You can also do this in the grid_ColumnAdded event handler .

  if (e.Column.HeaderText == "YourColumnHeaderText") 
    {
     e.Column.DefaultCellStyle.Format = "C2";
    }
+2
source

Rob GridView (-), DataGridView ( winforms).

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;

:

  • The DataSource is installed at the end of the column definitions - this is because the DataGridView automatically binds the data when it is installed.
  • Columns are set to DataGridViewTextBoxColumns. This is the standard way to display textual information in a DataGridView. If you use a DataGridViewColumn then it will not know how to display the data.
+2
source

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


All Articles