将项目从一个lisbox删除到另一个vb.net

时间:2017-10-21 21:02:27

标签: vb.net

我正在尝试从一个列表框中选择项目,删除它们,然后单击按钮并将它们插入另一个列表框。我被卡住了,因为它删除了项目,但他们没有移动到第二个列表框。

Public Class frmShop
    Private Sub frmShop_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.BackColor = Color.LightGray

        With lstStock.Items
            .Add("Orange Juice")
            .Add("Pepper")
            .Add("Ham")
            .Add("Butter")
            .Add("Eggs")
            .Add("Bread")
            .Add("Tea")
            .Add("Coffee")
        End With
    End Sub

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        lstStock.Items.Add(txtAdd.Text)
    End Sub

    Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
        Me.Close()
    End Sub

    Private Sub btnMoveOver_Click(sender As Object, e As EventArgs) Handles btnMoveOver.Click
        lstStock.Items.RemoveAt(lstStock.SelectedIndex)
        lstBasket.Items.Add(lstStock.SelectedIndex)

        If lstStock.SelectedIndex = -1 Then
            MessageBox.Show("You must select an item", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

问题是你没有移动ListBox的项目。

您可以在btnMoveOver上使用以下解决方案,而不是当前代码:

Private Sub btnMoveOver_Click(sender As Object, e As EventArgs) Handles btnMoveOver.Click

    If lstStock.SelectedItems.Count < 1 Then
        MessageBox.Show("You must select an item", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Exit Sub
    End If

    lstBasket.Items.Add(lstStock.Items(lstStock.SelectedIndex))
    lstStock.Items.RemoveAt(lstStock.SelectedIndex)
End Sub

您还可以使用以下代码支持应用程序的用户:

Private Sub lstStock_SelectedValueChanged(sender As Object, e As EventArgs) Handles lstStock.SelectedValueChanged
    btnMoveOver.Enabled = CBool(lstStock.Items.Count > 0)
End Sub

对于此事件,如果股票的ListBox上没有其他项目,则禁用该按钮。

if声明中使用SelectedIndex的解决方案:

Private Sub btnMoveOver_Click(sender As Object, e As EventArgs) Handles btnMoveOver.Click

    If lstStock.SelectedIndex < 0 Then
        MessageBox.Show("You must select an item", "Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Exit Sub
    End If

    lstBasket.Items.Add(lstStock.Items(lstStock.SelectedIndex))
    lstStock.Items.RemoveAt(lstStock.SelectedIndex)
End Sub