0

I have a DataGridView that I would like to fill programmatically. By creating a DataTable and binding it through a BindingSource to a DataGridView, the columns in the DataGridView are created as TextBoxColumns. A code sample below:

Dim dataTable As DataTable = New DataTable()
dataTable.Columns.AddRange(New DataColumn() {New DataColumn("TextBoxColumn1"),
                                             New DataColumn("TextBoxColumn2"),
                                             New DataColumn("ComboBoxColumn"),
                                             New DataColumn("TextBoxColumn3"),
                                             New DataColumn("TextBoxColumn4")})

Dim bindingSource As BindingSource = New BindingSource
bindingSource.DataSource = dataTable
dataGridView.DataSource = bindingSource

What is the best way to make the column "ComboBoxColumn" a ComboBoxColumn in the DataGridView?

I could create a ComboBoxColumn in the DataGridView manually and then bind it to a DataColumn, but I would like to know if there's a better way, like setting a property in the DataColumn or something like that.

joharei
  • 578
  • 1
  • 5
  • 22
  • [This answer](http://stackoverflow.com/a/7471347/209668) shows how to add a [DataGridViewComboBoxColumn](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxcolumn.aspx) to your `dataGridView`. – Codesleuth Jun 28 '13 at 08:07
  • Thanks, but it's not exactly what I'm looking for because the columns in the `DataGridView` are created when the grid is bound to data; I don't add them myself – joharei Jun 28 '13 at 08:19
  • Of course, I could maybe replace the auto generated column later on. – joharei Jun 28 '13 at 08:20
  • That's how I would suggest you do it. Grab it by name then replace it with a new DataGridViewComboBoxColumn. – Codesleuth Jun 28 '13 at 10:09

1 Answers1

2

Following @Codesleuth's suggestion, I replaced the auto generated DataGridViewTextBoxColumn with a DataGridComboBoxColumn like this:

Dim comboBoxColumn As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn()
comboBoxColumn.DataPropertyName = "ComboBoxColumn"
comboBoxColumn.DataSource = comboBoxBindingSource
comboBoxColumn.DisplayMember = "ComboBoxColumn"
comboBoxColumn.ValueMember = "ComboBoxColumn"
DataGridView.Columns.RemoveAt(COLUMN_INDEX)
DataGridView.Columns.Insert(COLUMN_INDEX, comboBoxColumn)
joharei
  • 578
  • 1
  • 5
  • 22
  • you should accept this answer even though it was your own to help show that it has been solved. Thanks! – Rachael Dec 21 '15 at 18:13