isxaker isxaker - 1 year ago 510
C# Question

Set selectedValue in DataGridViewComboBoxColumn

I have two tables: columns and tables (foreign key - Table_ID). I want to show columns in dataGridView with combobox. In combobox to be displayed related table (name tables) and selected item be value that set in columns.

List<columns> columns = DataLoader.GetColumns();
List<tables> tables = DataLoader.GetTables();

this.editingDataGridView.DataSource = columns; // my dataGridView
DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();

comboBoxColumn.DisplayMember = "Table_Name";
comboBoxColumn.ValueMember = "Table_ID";
comboBoxColumn.DataSource = tables;

//add combobox column in dataGrid

//AND this i want set value
int index = this.editingDataGridView.Columns.IndexOf(comboBoxColumn);
for (int i = 0; i < columns.Count; i++)
this.editingDataGridView.Rows[i].Cells[index].Value = columns[i].Table_ID;

After run, I get gridView with combobox column with dataSource, but without selected default value!
enter image description here

Answer Source

The key poin is

comboBoxColumn.DataPropertyName = "Table_ID";

Need to set DataPropertyName of dataGridComboBoxColumn

More this

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download