Instead of adding a cell to your grid, add a DataGridViewComboBox
column.
DataGridViewComboBoxColumn c = new DataGridViewComboBoxColumn(); c.Name = "ComboColumn"; c.DataSource = dataTable; c.ValueMember = "ID"; c.DisplayMember = "Item"; dataGridView1.Columns.Add(c);
To select a specific value, you set the Value property for this cell.
dataGridView1.Rows[rowIndexYouWant].Cells["ComboColumn"].Value = 1;
Please note that this type is important! In the comments, you say you get a System.FormatException
. This may be caused by setting the wrong type to value.
When you set the value to 1, you assign int - if for some reason you have rows in the ID column, you will get a System.FormatException
exception that you see.
If the types are different, you need to either update the DataTable definition or set a value for the string:
dataGridView1.Rows[rowIndexYouWant].Cells["ComboColumn"].Value = "1";
- Also note that this value must be present in the ID DataTable column that you set as the grid source.
As a rule, it is easiest to work with a DataGridView
when it has its own data set. In this case, you can associate the ComboBoxColumn with the DataSource network using the DataPropertyName property.
c.DataPropertyName = "GridDataSourceColumnName";
This allows you to use the value of the columns from the grid data source and for changes to the column to directly change this data source.
Finally, do not use the CellFormatting event here - this event is not intended for such use. It is usually best to do this work in the DataBindingComplete event (if you want it to be done once) or during some event, such as DefaultValues ββor RowValidating.
Using CellFormatting, you probably won't be able to manually edit the combo box for users.
source share