我有一个datagridview,我已经以编程方式填充,我想知道如何使其中一列符合指定的格式 - “C2”。
可以在分配数据源后完成吗?
干杯。
答案 0 :(得分:3)
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();
答案 1 :(得分:2)
您也可以在 grid_ColumnAdded事件处理程序中执行此操作。
if (e.Column.HeaderText == "YourColumnHeaderText")
{
e.Column.DefaultCellStyle.Format = "C2";
}
答案 2 :(得分:2)
Rob的答案是针对GridView(Web控件)而不是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;
注意事项: