2009-05-22 274 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中不存在先前的列。