Search code examples
c#winformsdatagridviewdatagridviewcomboboxcell

c# set which item is selected in datagridview combobox cell


I have two forms, in one I fill DataGridView with some rows, each row has two comboboxes.

I am able to get both value and formatted value from these cells, however when I try to copy all of this data into the next DataGridView that is in different form, I am unable to tell him which item from the ComboBox should be marked as selected.

When I was looking around I found these lines of code (unfortunately they were from 6+ years ago)

dataGridView.Rows[index].Cells[3].Value = ImageFormat.Items[1];

(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = ImageFormat.Items[0];

DataGridViewComboBoxCell comboboxFormat = (DataGridViewComboBoxCell)(dataGridView.Rows[index].Cells[3]);

comboboxFormat.Value = ImageFormat.Items[0];

(dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Value = (dataGridView.Rows[index].Cells[3] as DataGridViewComboBoxCell).Items[0];

Unfortunately none of these worked and most if not all threw "DataGridViewComboBoxCell value is not valid" exception

Maybe it's worth to mention that the possible items are binded from database like so:

string stm = "SELECT * FROM colours";
            using var cmd = new SQLiteCommand(stm, MainWin.con);
            SQLiteDataAdapter rdr = new SQLiteDataAdapter(cmd);
            DataTable dataTableColour = new DataTable();
            rdr.Fill(dataTableColour);

            stm = "SELECT * FROM formats";
            using var cmdd = new SQLiteCommand(stm, MainWin.con);
            SQLiteDataAdapter reader = new SQLiteDataAdapter(cmdd);
            DataTable dataTableFormat = new DataTable();
            reader.Fill(dataTableFormat);

            ImageFormat.ValueMember = "id";
            ImageFormat.DisplayMember = "name";
            ImageFormat.DataSource = dataTableFormat;

            ColourImage.ValueMember = "id";
            ColourImage.DisplayMember = "name";
            ColourImage.DataSource = dataTableColour;

Solution

  • Your datagridview should be bound to some datatable (let's say ImageFiles). Set ColourImage/ImageFormat combo's .DataPropertyName property to be the name of the column in the [ImageFiles] datatable that the combo should edit. Don't try to interact with the DGVCombo directly; just interact with the datatable to which the grid is bound

    enter image description here