简体   繁体   中英

Create a DataGridView with ComboBoxColumn from a DataTable

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM