我在WinForm应用程序中使用DataGridView来显示数据表。除了DataColumn的Caption属性外,一切正常。我试图设置Caption属性,但似乎DataGridView使用DataColumn的Name作为标题而不是Caption属性的值?
谷歌为此而且似乎故意禁用此标题属性。
我的WinForm应用程序是本地化的,我需要用中文显示标题。任何人都知道我该怎么做?
以下是我设置数据表的代码
// Create a new DataTable.
DataTable table = new DataTable("Payments");
// Declare variables for DataColumn and DataRow objects.
DataColumn column;
DataRow row;
// Create new DataColumn, set DataType,
// ColumnName and add to DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
column.Caption = LocalizedCaption.get("id") //LocalizedCaption is my library to retrieve the chinese caption
// Add the Column to the DataColumnCollection.
table.Columns.Add(column);
// Create three new DataRow objects and add them to the DataTable
for (int i = 0; i <= 2; i++)
{
row = table.NewRow();
row["id"] = i;
table.Rows.Add(row);
}
//assign the DataTable as the datasource for a DataGridView
dataGridView1.DataSource = table;
答案 0 :(得分:3)
您有几个选择。这是一个应该有效的快速修复,只需在代码块的末尾添加:
//Copy column captions into DataGridView
for (int i = 0; i < table.Columns.Count; i++) {
if (dataGridView1.Columns.Count >= i) {
dataGridView1.Columns[i].HeaderText = table.Columns[i].Caption;
}
}
如您所见,这只是将现有列标题复制到每个DataGridView列的正确HeaderText属性中。这假设在绑定DataTable之前DataGridView中不存在先前的列。
答案 1 :(得分:1)
这对我有用:
private void DataGrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
var dGrid = (sender as DataGrid);
if (dGrid == null) return ;
var view = dGrid.ItemsSource as DataView;
if (view == null) return;
var table = view.Table;
e.Column.Header = table.Columns[e.Column.Header as String].Caption;
}