2009-05-22 245 views
1

我在WinForm应用程序中使用DataGridView来显示数据表。一切工作正常,除了DataColumn的标题属性。我试图设置Caption属性,但似乎DataGridView使用DataColumn的名称作为标题,而不是Caption属性的值?如何为DataGridView设置标题

有谷歌为此,似乎这个标题属性是故意禁用。

我的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; 

回答

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; 
} 
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中不存在先前的列。