備註
ToolStrip 控制項會取代 ToolBar 控制項並加入其他功能,不過您也可以選擇保留 ToolBar 控制項,以提供回溯相容性及未來使用。 如需詳細資訊,請參閱 Windows Forms DataGridView 和 DataGrid 控制項之間的差異。
您可以使用 GridColumnStylesCollection 和 DataGridColumnStyle 物件 (它們是 DataGridTableStyle 類別的成員) 的屬性和方法以程式設計方式刪除或隱藏 Windows Forms DataGrid 控制項中的資料行。
已刪除或隱藏的資料行仍存在於方格所繫結的資料來源中,而且仍然可以透過程式設計方式來存取。 它們只是在資料格中不再被看見而止。
備註
如果您的應用程式不存取某些資料行,且您不希望它們顯示在資料格中,那麼可能沒有必要先將它們包含在資料來源中。
以程式設計方式從 DataGrid 中刪除資料行
在表單的宣告區域中,宣告 DataGridTableStyle 類別的新執行個體。
將 DataGridTableStyle.MappingName 屬性設定為資料來源中要套用樣式的資料表。 以下範例會使用 DataGrid.DataMember 屬性,並假定該屬性已設定。
將新的 DataGridTableStyle 物件新增至 datagrid 的資料表樣式集合中。
呼叫 DataGrid 的 GridColumnStyles 集合的 RemoveAt 方法,並指定要刪除的資料行的資料行索引。
' 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 類別的新執行個體。
將 DataGridTableStyle 的 MappingName 屬性設定為資料來源中要套用樣式的資料表。 以下程式碼會使用 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; }