如何:將資料表和資料行加入至 Windows Form DataGrid 控制項
注意
DataGridView 控制項會取代 DataGrid 控制項並加入其他功能,不過您也可以選擇保留 DataGrid 控制項,以提供回溯相容性及未來使用。 如需詳細資訊,請參閱 Windows Forms DataGridView 和 DataGrid 控制項之間的差異。
您可以藉由建立 DataGridTableStyle 物件,並將其新增至 GridTableStylesCollection 物件,以在資料表和資料行的 Windows Forms DataGrid 控制項中顯示資料,該物件是透過 DataGrid 控制項的 TableStyles 屬性存取。 每個資料表樣式都會顯示 DataGridTableStyle 物件的 MappingName 屬性中所 指定之任何資料表 的內容。 根據預設,沒有指定資料行樣式的資料表樣式會顯示該資料表中的所有資料行。 您可以將 DataGridColumnStyle 物件新增 至 GridColumnStylesCollection 物件,以限制資料表中出現的資料行,該物件是透過 每個 DataGridTableStyle 物件的 GridColumnStyles 屬性來存取。
以程式設計方式將資料表和資料行加入 DataGrid
若要在資料表中顯示資料,您必須先將 DataGrid 控制項系結至資料集。 如需詳細資訊,請參閱 如何:將 Windows Forms DataGrid 控制項系結至資料來源 。
警告
以程式設計方式指定資料行樣式時,請一律建立 DataGridColumnStyle 物件,並將其新增至 GridColumnStylesCollection 物件,然後再將 DataGridTableStyle 物件新增 至 GridTableStylesCollection 物件。 當您將空 的 DataGridTableStyle 物件新增至集合時, 會自動為您產生 DataGridColumnStyle 物件。 因此,如果您嘗試將具有重複 MappingName 值的新 DataGridColumnStyle 物件加入 GridColumnStylesCollection 物件,就會擲回例外狀況。
宣告新的表格樣式,並設定其對應名稱。
Dim ts1 As New DataGridTableStyle() ts1.MappingName = "Customers"
DataGridTableStyle ts1 = new DataGridTableStyle(); ts1.MappingName = "Customers";
DataGridTableStyle* ts1 = new DataGridTableStyle(); ts1->MappingName = S"Customers";
宣告新的資料行樣式,並設定其對應名稱和其他屬性。
Dim myDataCol As New DataGridBoolColumn() myDataCol.HeaderText = "My New Column" myDataCol.MappingName = "Current"
DataGridBoolColumn myDataCol = new DataGridBoolColumn(); myDataCol.HeaderText = "My New Column"; myDataCol.MappingName = "Current";
DataGridBoolColumn^ myDataCol = gcnew DataGridBoolColumn(); myDataCol->HeaderText = "My New Column"; myDataCol->MappingName = "Current";
呼叫 GridColumnStylesCollection 物件的 Add 方法 ,將資料行新增至表格樣式
ts1.GridColumnStyles.Add(myDataCol)
ts1.GridColumnStyles.Add(myDataCol);
ts1->GridColumnStyles->Add(myDataCol);
呼叫 GridTableStylesCollection 物件的 Add 方法 ,將資料表樣式新增至資料格。
DataGrid1.TableStyles.Add(ts1)
dataGrid1.TableStyles.Add(ts1);
dataGrid1->TableStyles->Add(ts1);
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應