Search code examples
c#winformsdatagridviewdataadapterdatagridviewcombobox

Change DataGridViewColumn to DataGridViewComboBoxColumn in bound DataGridView


I have a DataGridView bound to a DataTable and I use a SQLiteDataAdapter to update one SQLite database. I'm trying to make one of the columns a DataGridViewComboBoxColumn, but despite I can put items on it and change its cell values I'm no longer able to update it trough the DataAdapter.

I'm doing this once the DataGridView is loaded:

DataGridViewComboBoxColumn cbCol = new DataGridViewComboBoxColumn();
dataGridView1.Columns.Insert(2, cbCol);
dataGridView1.Columns[2].HeaderText = dataGridView1.Columns[3].HeaderText;
dataGridView1.Columns[3].Visible = false;

string[] cbList = new[] {"item1","item2"};

foreach (string str in cbList)
{
    cbCol.Items.Add(str);
}

for (int i = 0 ; i<= dataGridView1.Rows.Count - 1; i++)
{
    dataGridView1.Rows[i].Cells[2].Value = dataGridView1.Rows[i].Cells[3].Value;
}

The problem is that the ComboBoxColumn is not bound to the DataTable and I have to check for changes and modify the hidden column before running the DataAdapter.Update.

Is there any way to avoid this? Perfect scenario would be something like this:

    private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
    {
       if (columnadded.headertext == "xxx")
       {
           //Then this is column is the same but in a ComboBox format.
           //The ComboBoxColumn, when added, must show the same values and have 
           //the same binding as if if was the regular column.
       }
    }

Solution

  • Create the DataGridViewComboBoxColum, add it to the grid and bind the data. If you set the DataPropertyName property of your column to the db column id then when your data is bound, that data column will get bound to your grid column. The DataGridView will generate other columns automatically (if you set AutoGenerateColumns=true). Bind a second datasource to the comboboxcolumn itself.

    DataGridViewComboBoxColumn col1 = new DataGridViewComboBoxColumn ();
    col1.Name = //name of the column
    col1.HeaderText = //header text of the column
    col1.DataPropertyName = //db column id
    col1.DataSource = // datasource for combo
    dataGridView1.Columns.Add(col1);
    
    dataGridView1.AutoGenerateColumns = true;
    dataGridView1.DataSource = // your datasource