DataGridViewComboBoxColumn should always have all possible values โโin the list of combobox items or it will throw "FormatException: DataGridViewComboBoxCell value is not valid".
If you are trying to return values โโselected from a single combobox column, you can handle the CellParsing DataGridView event and get the selected item from DataGridView.EditingControl, because it will be set to edit the control from the edited column. Here is an example:
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e) { if (dataGridView1.CurrentCell.OwningColumn is DataGridViewComboBoxColumn) { DataGridViewComboBoxEditingControl editingControl = (DataGridViewComboBoxEditingControl)dataGridView1.EditingControl; e.Value = editingControl.SelectedItem; e.ParsingApplied = true; } }
You can also configure the way objects are displayed in each cell by handling the cell formatting event, here is the code that displays toString for any object or interface.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.Value != null) { e.Value = e.Value.ToString(); e.FormattingApplied = true; } }
The processing of these two events should be sufficient to display and edit data in any business object and its lighter, and then a record type converter. For this to work, set the DataGridView and the combobox column as follows:
var data = (from item in someTable select new { Foo = item.foo, Bar = item.Bar }).ToList(); grid.DataSource = data; column.DataPropertyName = "Foo"; column.DataSource = (from foo in Foo select foo).ToList ();
No need to set the DisplayMember or ValueMember property, just make sure that the combobox list of data sources has all the possible values โโfor Foo.
Hope this helps.
source share