c#datagridview从列表/字典/ datatable的组合框列datasouce [英] c# datagridview combobox column datasouce from list/dictionary/datatable
问题描述
我确定这个简单,但我已经花了一个大约每天1/2的谷歌和尝试各种东西。
I'm sure this simple but i've spent a about 1/2 a day googling and trying various things out.
我有一个datatable和一列是另一个数据库表的整数ID外键。
I've got a datatable and one column is an integer ID foreign key to another database table.
我有一个datagridview,我想使用combobox列允许用户更改值。
I've got a datagridview and i'd like to use a combobox column to allow user to change value. But instead of using the integers, it would be great to use the names.
我试过用public成员创建一个简单的结构int ID和string Name;一个字典,并查看枚举(但值在编译时未知),但没有任何工作。
I've tried creating a simple struct with public members int ID and string Name; a dictionary and looked into enums (however values not known at compile time) but not got anything to work yet.
我能够填充组合框与结构值,但无法以编程方式设置所选项目/索引;即,如果ID5在数据表中,则将组合框选择项设置为ID为5的struct。
I was able to populate the combobox with struct values, but not able to programmatically set the selected item/index; ie, if ID "5" is in the datatable, set the combo box selected item to the struct that has an ID of 5.
因此,为了清楚我需要:
So to be clear i'm wanting:
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,每个选择的项目应该匹配。
Datagridviewcombobox column should be loaded with three items; should display as "Name 1, Name 2, Name 3". Based on the gridview datasource's FK id, the selected item for each should match.
帮助?
/ p>
Andrew
推荐答案
您可以设置 DataGridViewComboBoxColumn.DataSource
属性,然后使用 ValueMember
和 DisplayMember
属性来确定显示的内容 ComboBox
。最简单的可能是将您的FK值加载到 DataTable
中,并将其用作数据源。例如:
You can set the DataGridViewComboBoxColumn.DataSource
property, and then use the ValueMember
and DisplayMember
properties to determine what is shown in the ComboBox
. Easiest is probably to load your FK values into DataTable
and use that as the data source. For your example:
// 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
,但您可以将 DataGridViewComboBox
列与原始< $ c> DataTable 使用 DataPropertyName
:
I am not sure how you are binding your DataGridView
to your initial DataTable
, but you can associate the DataGridViewComboBox
column with a specific column in your original DataTable
using DataPropertyName
:
fkCol.DataPropertyName = "ColumnName";
这篇关于c#datagridview从列表/字典/ datatable的组合框列datasouce的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!