Tutorial :Retrieving items from — DataGridViewComboBoxColumn


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:

    private Dictionary<int, ComboBox> comboBoxes;      public Form1()      {          InitializeComponent();          this.comboBoxes = new Dictionary<int, ComboBox>();          this.dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);      }        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)      {          var cb = e.Control as ComboBox;          if (!(this.comboBoxes.ContainsKey(this.dataGridView1.CurrentRow.Index)))          {              this.comboBoxes.Add(this.dataGridView1.CurrentRow.Index, cb);          }      }  

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.


You cant :(

This is a limitation of the DataGridViewComboBoxColumn.

I worked around this by creating a TypeDescriptor that adds an extra item called 'this', that returns the instance.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »