How do I select a value in a DataGridViewComboBoxCell?

Viewed 35065

I have DataGridViewComboBoxCell and a DataTable. The data in Table I bound with DataGridViewComboBoxCell using DataSource and set ValueMember, and DisplayMember.

private void Form1_Load(object sender, EventArgs e)
{         
    DataGridViewComboBoxCell comboBoxCell = new DataGridViewComboBoxCell();

    dataGridView1.Rows[0].Cells[0] = comboBoxCell;

    comboBoxCell.DataSource = dataTable;
    comboBoxCell.ValueMember = "ID";
    comboBoxCell.DisplayMember = "Item";
}

How can I programmatically set the value in the cell when the form loads? In the simple ComboBox I know a property SelectedIndex. I tried comboBoxCell.Value = ...; but it gives an exception. And tried

private void dataGridView1_CellFormatting(object sender, 
    DataGridViewCellFormattingEventArgs e)
{
    e.Value = 1;
}

It sets a new value in the cell, but I need to select a value.

Form loaded and I have empty cell.

Form loaded and I have empty cell.

And some data in the ComboBox.

And some data in the ComboBox.

When I put this code dataGridView1.Rows[0].Cells["ComboColumn"].Value = "1"; right after comboBoxCell.DisplayMember = ... (see above), it works fine.

The value "1" in the ID column corresponds to the value "Second" in the Items column.So, I get the correct result.

The value "1" in the ID column corresponds to the value "Second" in the Items column.So, I get the correct result.

Sorry for my English and my newbie code :)

1 Answers
Related