I've got a datatable and one column is an integer ID foreign key to another database table.
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.
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.
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 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.
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";
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With