使用DataTable中的ComboBoxColumn创建DataGridView

时间:2013-06-28 08:01:00

标签: .net vb.net datagridview datatable datagridviewcombobox

我想要以编程方式填写DataGridView。通过创建DataTable并将其BindingSource绑定到DataGridViewDataGridView中的列将创建为TextBoxColumns。下面的代码示例:

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

ComboBoxColumn中将“ComboBoxColumn”列设为DataGridView的最佳方法是什么?

我可以手动在ComboBoxColumn中创建DataGridView,然后将其绑定到DataColumn,但我想知道是否有更好的方法,例如设置属性DataColumn或类似的东西。

1 个答案:

答案 0 :(得分:2)

根据@ Codesleuth的建议,我将自动生成的DataGridViewTextBoxColumn替换为DataGridComboBoxColumn,如下所示:

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)