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

DataGridView bound to list(of T) change column type

我有一个 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

    ....

列表中的所有项目代表一个具有多个属性的对象,其中之一是 material As String。我有大量可用的 material 列表,用户应该可以从中进行选择。我怎样才能在 datagridview 作为下拉框中使用它?

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

您无法更改列类型,因此在创建列后将 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 来实现。

使用包含 Id 和您要显示的文本的 DataTable 查询结果,或者使用简单的 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 的数据类型需要与其映射到数据源中的列的数据类型相匹配 (cbo.DataPropertyName)