我想要以编程方式填写DataGridView
。通过创建DataTable
并将其BindingSource
绑定到DataGridView
,DataGridView
中的列将创建为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
或类似的东西。
答案 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)