我在尝试使用多个表单将数据从一个列表框复制到另一个列表框时遇到问题,这些表单是全局变量和数组的模块。此时它告诉我,当我选择和项目形成辅助列表框并尝试将其发送到我的主列表框时,它表示我超出了数组的范围。我已尝试过各种不同的方法,但还没有提出解决方案。我知道这可能是显而易见的,但还没有打到我。
这就是我启动数组以使用
填充辅助列表框的方法Public mp3Albums() As String = {" Tres Hombres ZZ TOP ", " Fandango! ZZ TOP ", " Soul Kiss Tom Duda ", " Instrumental Telepathy Tom Duda ", " Dark Side of the Moon Pink Floyd ", " Seventh Sojourn Moody Blues ", " In Search of the lost Chord Moody Blues "}
我的主窗体中的列表框名为lstShoppingCart
这是我填充和按钮单击操作以尝试将数据复制到我的主列表框的方式。忽略试图复制的第二组数据的调用,因为如果我不能只复制一个,那么我没有业务试图复制2套标题和价格。除非它比我想象的更简单
Dim frmMain As New MainForm
frmMain.lstShoppingCart.Items.Add("A" & lstVinylAlbum.SelectedIndex & ": " & lstVinylAlbum.SelectedItem.ToString)
答案 0 :(得分:1)
从表示列表框中项目的小类开始:
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对象。