0

我有一个组合框,可以从逗号分隔的文件中获取不同的数据。我需要使用该不同的数据并填充第二个组合框,其中仅包含有关第一个组合框的信息。示例:这是我的逗号分隔文件文本。

Jenny, 25, Female
Micheal, 100, Female, hdfgh
shaun, 50, male
Cindy, 75, Female
Jenny, 25, Female
Micheal, 100, Female
shaun, 50, male
Cindy, 50, Female
Carry, 75, Female

这是我的代码:

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Call combo1()
    Call combo2()
End Sub

Sub combo1()
    ' a set to store the names
    Dim names = New HashSet(Of String)
    Using reader = New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\here.txt")

        reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
        reader.Delimiters = New String() {","}
        Dim currentRow As String()
        While Not reader.EndOfData
            Try
                ' read rows and add first field to set
                currentRow = reader.ReadFields()
                names.Add(currentRow(0).ToString())
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                ' do something
            End Try
        End While
    End Using

    ' bind data to combo box (or use Items.Add instead)
    ComboBox1.DataSource = names.ToList()
End Sub

Sub combo2()
    ' a set to store the names
    Dim names = New HashSet(Of String)
    Using reader = New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\here.txt")

        reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
        reader.Delimiters = New String() {","}
        Dim currentRow As String()
        While Not reader.EndOfData
            Try
                ' read rows and add first field to set
                currentRow = reader.ReadFields()
                names.Add(currentRow(1).ToString())
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                ' do something
            End Try
        End While
    End Using

    ' bind data to combo box (or use Items.Add instead)
    ComboBox2.DataSource = names.ToList()
End Sub

这可以很好地将不同的数据填充到每个组合框中,但我希望第二个组合框仅填充组合框 1 中所选项目的数据,例如,如果我选择“Cindy”,则下一个组合框必须只显示 25 和 75,而不是所有不同的结果

4

1 回答 1

2

按照您的方式绑定第一个组合框。捕获组合框SelectedValueChanged事件。使用该SelectedValue属性,对文件进行第二次传递。这次将值添加到不同的哈希集中,如下所示:

Dim ages = New HashSet(Of String)
    Using reader = New Microsoft.Visua...   ...FieldParser("C:\here.txt")

        reader.TextFieldType = Micros...   ....eldType.Delimited
        reader.Delimiters = New String() {","}
        Dim currentRow As String()
        While Not reader.EndOfData
            Try
                '   v--- THIS LINE IS IMPORTANT ---v
                if currentRow(0).ToString() = combobox1.selectedvalue then

                    ages.Add(currentRow(1).ToString())
                end if

你明白了

    ' bind data to combo box (or use Items.Add instead)
    ComboBox2.DataSource = ages.ToList()

write acceptance code in ComboBox2 SelectedValueChanged

于 2013-08-27T17:21:37.747 回答