首页 > 解决方案 > 多选列表框最后点击的项目到文本框

问题描述

我想在具有多选的 ListBox 上显示最后单击的项目。当我使用以下内容时,它仅显示所选列表中的第一项:

Textbox1.text = listbox1.text

标签: vb.net

解决方案


我认为您唯一的选择是存储所选索引的列表,并在选择更改时添加/删除它。

像这样的东西应该可以完成这项工作(假设 WinForms):

Private selectedIndices As New List(Of Integer)

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    ' Add the newly selected items.
    selectedIndices.AddRange(
        ListBox1.SelectedIndices.Cast(Of Integer).
                                 Where(Function(i) Not selectedIndices.Contains(i)))
    ' Remove the unselected items.
    selectedIndices.RemoveAll(Function(i) Not ListBox1.SelectedIndices.Contains(i))

    ' Update the TextBox text. You can move this code to a different method
    ' if you want to trigger it using a button or something.
    If selectedIndices.Count = 0 Then
        TextBox1.Text = String.Empty
    Else

        Dim lastIndex As Integer = selectedIndices.Last()
        TextBox1.Text = ListBox1.GetItemText(ListBox1.Items(lastIndex))
    End If
End Sub

看看它的实际效果:

演示


推荐阅读