首页 > 解决方案 > 使两个组合框的输入从 csv 文件中搜索、读取和显示数据

问题描述

看这个问题可能会没有答案或真的很混乱。这一切都在 Visual Studio 中(首选 VB 代码)。

布局

我有这个程序,基本上当程序加载时,我希望组合框填充来自 CSV 文件的数据(我已经这样做了。)然后,一旦我从部分框中选择一个值,我想要竞争对手编号组合框仅显示具有从部分框中选择的值的数字(即从属组合框)。然后根据选择的两个值,我希望显示一个名称。

因此,如果选择第 1 节,竞争对手 1,我希望显示他们的名字。但是如果我将其更改为第 1 节的竞争对手 2,名称应该会更改。

标签: vb.netwinformscsvcombobox

解决方案


为您的竞争对手对象构建一个类。

Public Class Person
    Public Property ComboBox1Value As String
    Public Property ComboBox2Value As String
    Public Property Name As String
End Class

然后声明一个集合以在某处保存对象列表。我将它添加到 Form1.vb 的顶部。现在,当您点击 Search_For_Name 子时,只需遍历集合,直到组合框值与其中一个对象中的值匹配。

Public Class Form1

    Dim MyCollection As New Collection

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        'Populate your collection here from your csv by declaring a new
        'person for each row of your file, and then adding it to the 
        'collection.
    End Sub

    Private Sub ComboBox1_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedValueChanged
        Search_For_Name()
    End Sub

    Private Sub ComboBox2_SelectedValueChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedValueChanged
        Search_For_Name()
    End Sub

    Private Sub Search_For_Name()
        For Each P As Person In MyCollection
            If P.ComboBox1Value = ComboBox1.Text And P.ComboBox2Value = ComboBox2.Text Then
                TextBox1.Text = P.Name
                Exit For
            End If
        Next
    End Sub

End Class

推荐阅读