在DataGridViewComboBoxColumn中设置selectedValue

时间:2013-08-19 13:15:40

标签: c# winforms gridview combobox

我有两个表:列和表(外键 - Table_ID)。我想用multicobox在dataGridView中显示列。在组合框中显示相关表(名称表),所选项目是在列中设置的值。

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
this.editingDataGridView.Columns.Add(comboBoxColumn);

//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;
}

运行后,我使用带有dataSource的combobox列获得gridView,但没有选择默认值! enter image description here

2 个答案:

答案 0 :(得分:2)

关键点是

comboBoxColumn.DataPropertyName = "Table_ID";

需要设置dataGridComboBoxColumn的DataPropertyName

More this

答案 1 :(得分:0)

在vb.net中,我找到了这个解决方案

Dim cbx As DataGridViewComboBoxCell = dgvEstudios.Rows(x).Cells(1)
cbx.Value = Trim("String value")