在2个列表框中选择相同的项目 - Visual Basic

时间:2015-08-03 04:12:10

标签: vb.net listbox

所以我有2个列表框,例如我将使用名称Jack,John和Joe。 这三个名字分别在2个列表框中,我希望能够选择Jack然后让它在第二个列表框中选择Jack。 这可能吗?如果是这样,有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

假设WinForms,并且您在列表框中存储了简单的字符串,并且顺序可能不同:

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    Dim i As Integer = ListBox2.FindString(ListBox1.SelectedItem)
    If (i <> -1 AndAlso ListBox2.SelectedIndex <> i) Then
        ListBox2.SelectedIndex = i
    End If
End Sub

Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
    Dim i As Integer = ListBox1.FindString(ListBox2.SelectedItem)
    If (i <> -1 AndAlso ListBox1.SelectedIndex <> i) Then
        ListBox1.SelectedIndex = i
    End If
End Sub

----------编辑----------

鉴于ListBox内容的变化,请尝试这样做:

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged, ListBox2.SelectedIndexChanged
    Dim lb1 As ListBox = If(sender Is ListBox1, ListBox1, ListBox2)
    Dim lb2 As ListBox = If(sender Is ListBox1, ListBox2, ListBox1)

    If lb1.SelectedIndex <> -1 Then
        Dim number As String = lb1.SelectedItem.ToString.Split().Last
        For i As Integer = 0 To lb2.Items.Count - 1
            If lb2.Items(i).ToString.StartsWith(number) Then
                If lb2.SelectedIndex <> i Then
                    lb2.SelectedIndex = i
                End If
                Exit For
            End If
        Next
    End If
End Sub

请注意,同一个处理程序正在处理ListBox1和ListBox2 SelectedIndexChanged()事件。