簡體   English   中英

來自list / dictionary / datatable的C#datagridview組合框列數據源

[英]C# datagridview combobox column datasource from list/dictionary/datatable

我有一個數據表,一列是另一個數據庫表的整數ID外鍵。

我有一個datagridview,我想使用組合框列來允許用戶更改值。 但是不使用整數,使用名稱會很棒。

我嘗試使用公共成員int ID和string Name創建一個簡單的結構; 一個字典,並查看枚舉(但在編譯時不知道的值),但還沒有任何工作。

我能夠使用struct值填充組合框,但無法以編程方式設置所選項/索引; 即,如果ID“5”在數據表中,則將組合框選定項設置為ID為5的結構。

所以要清楚我想要:

gridview datasource's fk ID's 
1
2
3

Foreign Key table:

ID   Name 
1    Name 1
2    Name 2
3    Name 3

Datagridviewcombobox列應該加載三個項目; 應顯示為“名稱1,名稱2,名稱3”。 根據gridview數據源的FK id,每個選定的項應該匹配。

您可以設置DataGridViewComboBoxColumn.DataSource屬性,然后使用ValueMemberDisplayMember屬性來確定ComboBox顯示的內容。 最簡單的可能是將您的FK值加載到DataTable並將其用作數據源。 對於你的例子:

// assuming your DataGridViewComboBox column is fkCol
// and your fk values are in a DataTable called fkTable
fkCol.DataSource = fkTable;
fkCol.ValueMember = "ID";
fkCol.DisplayMember = "Name";

我不確定您如何將DataGridView綁定到初始DataTable ,但您可以使用DataPropertyNameDataGridViewComboBox列與原始DataTable的特定列相關聯:

fkCol.DataPropertyName = "ColumnName";
    DataAccessLayer dal = new DataAccessLayer();
    DataTable movies = dal.GetMovies();

    gvMovies.DataSource = movies;
    gvMovies.AllowUserToAddRows = false;
    gvMovies.AllowUserToDeleteRows = false;

    //Create the new combobox column and set it's DataSource to a DataTable
    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
    col.DataSource = dal.GetMovieTypes(); ; 
    col.ValueMember = "MovieTypeID";
    col.DisplayMember = "MovieType";
    col.DataPropertyName = "MovieTypeID";

    //Add your new combobox column to the gridview
    gvMovies.Columns.Add(col);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM