DataGridView绑定到列表(T)更改列类型

时间:2017-01-04 14:29:45

标签: .net vb.net datagridview datagridviewcombobox

我有datagridview绑定到List(of T)

Private BodyComponents As New List(Of BodyComponent)
Private BodyBinding As BindingSource


Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()


    ' Set the bindingsource
    BodyBinding = New BindingSource(BodyComponents, Nothing)

    ' Add any initialization after the InitializeComponent() call.
    dgvBodyOverview.DataSource = BodyBinding

    ....

列表中的所有项目都代表具有多个属性的对象,其中一个属性为材质As String。我有一个很大的可用材料列表,用户应该可以从中选择。如何在datagridview下拉框中提供此功能?

信息:打开对话框时,在运行时读取材料,而不是硬编码。

1 个答案:

答案 0 :(得分:1)

您无法更改列类型,因此在创建列后,将Material替换为您创建的新DataGridViewComboBoxColumn

dgv1.DataSource = ...

Dim cbo = New DataGridViewComboBoxColumn()
Dim oldCol = dgv1.Columns("Material")
' copy or set prop values
cbo.HeaderText = oldCol.HeaderText
cbo.Name = oldCol.Name
cbo.DataSource = MaterialsList
cbo.DataPropertyName = "Material"

' replace the column
dgv1.Columns.Remove(oldCol)
dgv1.Columns.Add(cbo)
' cant set the Display Index until it is in the DGV
cbo.DisplayIndex = oldCol.DisplayIndex

如果你需要列显示一件事但是将类似Id的内容保存到DGV的DataSource,你可以通过组合列的DataSource来实现。

使用包含DataTable的{​​{1}}查询结果和您要显示的文字,或使用简单Id这些名称 - 值对:

List

cbo.DataSource = Materials ' == a DT or List of Name-Id cbo.DisplayName = "MaterialName" ' col or prop name to show cbo.ValueMember = "Id" ' value to save 的数据类型需要与它在数据源中映射到的列的数据类型相匹配(ValueMember

相关问题