我有一个组合框,可以从逗号分隔的文件中获取不同的数据。 我需要使用那些不同的数据并填充第二个组合框,其中只包含有关第一个组合框的信息。 例: 这是我逗号分隔的文件文本。
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并非所有不同的清除
答案 0 :(得分:2)
以你的方式绑定第一个组合框。捕获组合框SelectedValueChanged
事件。
使用SelectedValue
属性,对文件执行第二次传递。这次将值添加到不同的hashset,如下所示:
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()
在ComboBox2
SelectedValueChanged