根据列表框选择搜索不同的数组

时间:2016-02-06 10:15:55

标签: arrays vb.net

首先,这是我的代码:

Public Class Form1
    'Training I
    Dim Pabumon() As String = {"Motimon", "Yokomon", "Tanemon"}

    Private Sub Training1_SelectedIndexChanged_1(sender As System.Object, e As System.EventArgs) Handles Training1.SelectedIndexChanged
        Dim ArrayName As String = Training1.SelectedItem
        Dim HighSub As Integer = 0
        Training2.Items.Clear()

        For Each evo As String In ArrayName

            Training2.Items.Add(ArrayName(HighSub))
            HighSub += 1

        Next evo
    End Sub
End Class

我的目标是从数组中填充listbox2。我想从一个与listbox1中所选项目同名的数组填充。截至目前,它所做的就是拼出listbox1中所选索引的文本。我想要它做的是当我从listbox1中选择Pabumon时,将项目Motimon,Yokomon和Tanemon添加到listbox2。

1 个答案:

答案 0 :(得分:0)

试试这个。这样,当您向Training1列表添加更多项目时,您只需向listBoxItems添加一个新列表,如Form1_Load所示

listBoxItems将是要添加到Training2的项目列表。每个列表中的第一项是要添加到Training1

的列表的名称
Public Class Form1

    Dim listBoxItems As New List(Of String())

您可以在此处将列表添加到listBoxItems,然后将列表中的第一项添加到Training1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        listBoxItems.Add({"Pabumon", "Motimon", "Yokomon", "Tanemon"})
        listBoxItems.Add({"List2", "cat", "dog", "pig"})
        listBoxItems.Add({"List3", "cow", "Chicken", "Horse"})
        PopulateTraining1()
    End Sub

这将遍历listBoxItems中的每个列表,以将第一个项目添加到Training1

    Private Sub PopulateTraining1()
        For Each item As String() In listBoxItems
            Training1.Items.Add(item(0))
        Next
    End Sub

这将清除Training2,搜索listBoxItems,直到找到listName的匹配项,并将Training2与该列表中的其余项目一起填充。

    Private Sub PopulateTraining2(listName As String)
        Training2.Items.Clear()
        Dim tempList As New List(Of String)
        For Each training2List As String() In listBoxItems
            If training2List(0) = listName Then
                For listItems As Integer = 1 To training2List.Count - 1
                    Training2.Items.Add(training2List(listItems))
                Next
            End If
        Next
    End Sub

这与原始代码完成相同但使用新数据

    Private Sub Training1_SelectedIndexChanged_1(sender As System.Object, e As System.EventArgs) Handles Training1.SelectedIndexChanged
        Dim highSub As Integer
        PopulateTraining2(Training1.SelectedItem.ToString)
        highSub = Training2.Items.Count
    End Sub

End Class