I
I
isxaker2013-08-19 17:00:13
.NET
isxaker, 2013-08-19 17:00:13

How to set value in DataGridViewComboBoxColumn?

I want to display information from a table in a DataGridView, and in one of the columns, pull up a related table and display it as a DropDown sheet.

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

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

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

//add combobox column in dataGrid
this.editingDataGridView.Columns.Add(comboBoxColumn);

int index = this.editingDataGridView.Columns.IndexOf(comboBoxColumn);

//AND this i want set value
for (int i = 0; i < columns.Count; i++)
{
     //do not work; not set value from columns
      this.editingDataGridView.Rows[i].Cells[index].Value = columns[i].Table_ID;
}

In DropDown the data arrives correctly
DropDown.png
, but no value is set:
DDList.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
isxaker, 2013-08-23
@isxaker

That's where the key was

comboBoxColumn.DataPropertyName = "Table_ID";

Here we are explicitly naming the property that the comboBox and dataGridView will be bound to.

Y
Yurii Medvedev, 2013-08-20
@kin9pin

int index = this.editingDataGridView.Columns.IndexOf(comboBoxColumn);

can be replaced with
int index = comboBoxColumn.Index;

To set the value, you need to do like this:
(this.editingDataGridView.Rows[i].Cells[index] as DataGridViewComboBoxCell).Value = tables.FirstOrDefault(c =>c.Table_ID == columns[i].Table_ID);

provided that the Value property is set to an object that has public properties "Table_Name" and "Table_ID"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question