Suppose I have designed a DataGridView to have a comboBoxColumn named ‘dataGridViewComboBocColumn’.
I can populate the comboBox using the following code:
private void DataGridViewForm_Load(object sender, EventArgs e)
{
BookCollection books = Book.GetAllBooks();
foreach (Book b in books)
{
dataGridViewComboBocColumn.Items.Add(b);
}
dataGridViewComboBocColumn.DisplayMember = "BookName";
dataGridViewComboBocColumn.ValueMember = "BookISBN";
}
But how can I retrieve a selected item object. So that I can cast and convert that item into a Book – object.
Ok, here’s a little hack you can do. First, hook into the DataGridView’s EditingControlShowing event, and in the event handler the EventArgs has a property e.Control that can be cast to a standard ComboBox. So, keep a dictionary that is keyed by the int being the rowindex. Then, in the event handler, add the combo box to the dictionary:
Then, when you need to get the object out of the combobox, just iterate through your dictionary, and get the right combobox, and just get the SelectedItem / SelectedValue.