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

问题描述:

我有一个datagridview绑定到一个List(of T)DataGridView绑定到列表(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下拉框中提供此功能?

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

您不能更改列类型,所以列在创建后用新DataGridViewComboBoxColumn更换Material一个创建:

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 

在您需要的列中显示1案件但要将类似Id的内容保存到DGV的DataSource,您可以通过组合栏的DataSource来执行此操作。

使用其中任何一个包含要展示的Id和文本或简单的List这些名称 - 值对的DataTable查询结果:

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

+0

什么是最好使用时,没有替代'ID'需要?只需要显示和保存字符串。 –

+0

那是什么顶部 - 在人力资源上面 - 将MaterialsList设置为数据源 - 假设它是一个普通的'List(String)' - 你没有多说这是什么 – Plutonix

+0

字符串数组或列表将工作 – Plutonix