2011-10-31 44 views
4

我敢肯定这很简单,但我花了大约1/2天的谷歌搜索和尝试各种事情。c#datagridview从列表/字典/数据表datagridview combobox列datasouce

我有一个数据表,一列是另一个数据库表的整数ID外键。

我有一个datagridview,我想使用组合框列允许用户更改值。但不是使用整数,而是使用这些名称会很好。

我试着创建一个简单的结构与公共成员int ID和字符串名称;一个字典,并查看枚举(但在编译时不知道的值),但没有任何工作。

我能够使用结构体值填充组合框,但无法以编程方式设置所选项目/索引;即,如果ID“5”是在数据表中,设置选择项都具有的5

的ID的结构中的组合框所以要清楚即时想要:

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,每个选定的项目应该匹配。

帮助?

安德鲁

回答

9

您可以设置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,但你可以在你原有的DataTable使用DataPropertyNameDataGridViewComboBox柱与特定的列关联:

fkCol.DataPropertyName = "ColumnName"; 
+0

谢谢heas!每天搜索1/2,我需要的是另外2行代码 - DOH!这是行得通的。 – andrew

0
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);