Windows窗体应用程序根据组合框选择更改数据网格视图中的数据

时间:2018-01-10 10:35:46

标签: vb.net winforms visual-studio

对不起,我对Visual和学习学习有了新的认识,但我无法根据组合框中的选择更改数据网格视图中显示的数据。 任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

以下是LINQ和List(Of Producer) _allProducers )分配给DataGridView的数据源( grdProducers )和ComboBox( cmbProducers )的示例强>)

Class Producer
    Public Property ID As Integer
    Public Property NAME As String
    Public Property COMPANY_ID As Integer
End Class

Private _allProducers As List(Of Producer) = New List(Of Producer)

填写_allProducers列表:

_allProducers = {
      New Producer() With {.ID = 1, .NAME = "John", .COMPANY_ID = 2},
      New Producer() With {.ID = 2, .NAME = "Sam", .COMPANY_ID = 3},
      New Producer() With {.ID = 3, .NAME = "Smith", .COMPANY_ID = 2},
      New Producer() With {.ID = 4, .NAME = "Dan", .COMPANY_ID = 1}
    }.ToList()

Init ComboBox:

cmbProducers.DropDownStyle = ComboBoxStyle.DropDown
cmbProducers.DataSource = _allProducers
cmbProducers.DisplayMember = "NAME" 'value to display in combo
cmbProducers.ValueMember = "COMPANY_ID" 'value to return 

现在,您可以在SelectedIndexChanged ComboBox上设置cmbProducers事件。当SelectedIndex属性发生更改时,会发生此事件。

Private Sub cmbProducers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbProducers.SelectedIndexChanged
    if (IsNumeric(cmbProducers.SelectedValue)) Then 'check for numeric values
      grdProducers.DataSource = _allProducers.Where(Function(p) p.COMPANY_ID = cmbProducers.SelectedValue).ToList()
   EndIf
End Sub

在这种情况下,_allProducers List将被过滤,并返回COMPANY_ID等于在ComboBox中选择的值的所有对象。 我希望这可以帮到你。