从一个代表列表框中项目的小类开始:
Public Class ListItem
Private _key As String = String.Empty
Private _value As String = String.Empty
Public Sub New(ByVal key As String, ByVal value As String)
_key = key
_value = value
End Sub
Public ReadOnly Property Key() As String
Get
Return _key
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return _value
End Get
End Property
' Prevents the object type from displaying in the list box.
Public Overrides Function ToString() As String
Return _value
End Function
End Class
现在,让我们假设一个表单上有两个 ListBox 对象(lstLeft 和 lstRight),有两个按钮 - 一个用于向右移动项目,一个用于向左移动项目:
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
InitData()
End Sub
Private Sub InitData()
With lstLeft.Items
.Add(New ListItem("1", "Tres Hombres ZZ TOP"))
.Add(New ListItem("2", "Fandango! ZZ TOP"))
.Add(New ListItem("3", "Soul Kiss Tom Duda"))
.Add(New ListItem("4", "Instrumental Telepathy Tom Duda"))
End With
End Sub
Private Sub btnMoveRight_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveRight.Click
If lstLeft.SelectedItem IsNot Nothing Then
Dim selectedItem As ListItem = DirectCast(lstLeft.SelectedItem, ListItem)
lstRight.Items.Add(selectedItem)
lstLeft.Items.Remove(selectedItem)
End If
End Sub
Private Sub btnMoveLeft_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMoveLeft.Click
If lstRight.SelectedItem IsNot Nothing Then
Dim selectedItem As ListItem = DirectCast(lstRight.SelectedItem, ListItem)
lstLeft.Items.Add(selectedItem)
lstRight.Items.Remove(selectedItem)
End If
End Sub
End Class
这样做只是将所选 ListItem 对象的引用添加到“其他”ListBox,并从当前 ListBox 中删除对所选 ListItem 对象的引用。如果您想在两个单独的表单之间执行此操作,则每个表单都需要一个Public Property AddToList(item As ListItem)
函数。首先,调用对面窗体上的函数以添加到该窗体的 ListBox,然后从当前窗体中删除 ListItem 对象。