如何:刪除或隱藏 Windows Form DataGrid 控制項中的資料行
注意
DataGridView 控制項會取代 DataGrid 控制項並加入其他功能,不過您也可以選擇保留 DataGrid 控制項,以提供回溯相容性及未來使用。 如需詳細資訊,請參閱 Windows Forms DataGridView 和 DataGrid 控制項之間的差異。
您可以使用 和 DataGridColumnStyle 物件的屬性和方法 GridColumnStylesCollection ,以程式設計方式刪除或隱藏 Windows Forms DataGrid 控制項中的資料行(也就是 類別的成員 DataGridTableStyle )。
已刪除或隱藏的資料行仍存在於方格所系結的資料來源中,而且仍然可以以程式設計方式存取。 資料格中不再顯示它們。
注意
如果您的應用程式無法存取特定資料行,而且您不希望它們顯示在 datagrid 中,則可能不需要先將它們包含在資料來源中。
以程式設計方式從 DataGrid 刪除資料行
在表單的宣告區域中,宣告 類別的新實例 DataGridTableStyle 。
將 DataGridTableStyle.MappingName 屬性設定為您要套用樣式之資料來源中的資料表。 下列範例會使用 DataGrid.DataMember 屬性,它假設已設定此屬性。
將新的 DataGridTableStyle 物件新增至 datagrid 的資料表樣式集合。
RemoveAt呼叫 集合 GridColumnStyles 的 DataGrid 方法,指定要刪除之資料行的資料行索引。
' Declare a new DataGridTableStyle in the ' declarations area of your form. Dim ts As DataGridTableStyle = New DataGridTableStyle() Sub DeleteColumn() ' Set the DataGridTableStyle.MappingName property ' to the table in the data source to map to. ts.MappingName = DataGrid1.DataMember ' Add it to the datagrid's TableStyles collection DataGrid1.TableStyles.Add(ts) ' Delete the first column (index 0) DataGrid1.TableStyles(0).GridColumnStyles.RemoveAt(0) End Sub
// Declare a new DataGridTableStyle in the // declarations area of your form. DataGridTableStyle ts = new DataGridTableStyle(); private void deleteColumn() { // Set the DataGridTableStyle.MappingName property // to the table in the data source to map to. ts.MappingName = dataGrid1.DataMember; // Add it to the datagrid's TableStyles collection dataGrid1.TableStyles.Add(ts); // Delete the first column (index 0) dataGrid1.TableStyles[0].GridColumnStyles.RemoveAt(0); }
以程式設計方式隱藏 DataGrid 中的資料行
在表單的宣告區域中,宣告 類別的新實例 DataGridTableStyle 。
將 MappingName 的 DataGridTableStyle 屬性設定為您要套用樣式之資料來源中的資料表。 下列程式碼範例會使用 DataGrid.DataMember 已設定的屬性。
將新的 DataGridTableStyle 物件新增至 datagrid 的資料表樣式集合。
將資料
Width
行的 屬性設定為 0,以指定要隱藏之資料行的資料行索引,以隱藏資料行。' Declare a new DataGridTableStyle in the ' declarations area of your form. Dim ts As DataGridTableStyle = New DataGridTableStyle() Sub HideColumn() ' Set the DataGridTableStyle.MappingName property ' to the table in the data source to map to. ts.MappingName = DataGrid1.DataMember ' Add it to the datagrid's TableStyles collection DataGrid1.TableStyles.Add(ts) ' Hide the first column (index 0) DataGrid1.TableStyles(0).GridColumnStyles(0).Width = 0 End Sub
// Declare a new DataGridTableStyle in the // declarations area of your form. DataGridTableStyle ts = new DataGridTableStyle(); private void hideColumn() { // Set the DataGridTableStyle.MappingName property // to the table in the data source to map to. ts.MappingName = dataGrid1.DataMember; // Add it to the datagrid's TableStyles collection dataGrid1.TableStyles.Add(ts); // Hide the first column (index 0) dataGrid1.TableStyles[0].GridColumnStyles[0].Width = 0; }
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應