0

所以我试图使用一个列表框来访问我的二维数组中的变量。我不确定最好的方法是什么。现在我正在使用列表框的 selectedindex 来访问它,但我只看到第二个维度显示在我的消息框中。任何帮助,将不胜感激。

    Option Explicit On
    Option Strict On
    Option Infer Off

    Public Class Form1

        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

            lstInventory.Items.Add("Hand Grenade")
            lstInventory.Items.Add("9mm Ammo Box")
            lstInventory.Items.Add(".40 Ammo Box")
            lstInventory.SelectedIndex = 0

        End Sub

        Dim dblInventoryItem(,) As Double = {{10.99, 5},
                                    {5.99, 10},
                                    {8.99, 8}}


        Private Sub btnCheck_Click(sender As System.Object, e As System.EventArgs) Handles btnCheck.Click

            Dim intRow As Integer = lstInventory.SelectedIndex

            MessageBox.Show(dblInventoryItem(intRow, 1).ToString)




        End Sub
    End Class
4

1 回答 1

1

您不想在这里使用多维数组。

执行此操作的 OOP 方法是将库存项目定义为其自己的类或结构,并使用实例来填充您的列表框并存储库存项目的价格和数量。

就像是:

Public Class Form1

Structure InventoryItem
    Public Sub New(ByVal itmName As String, ByVal itmPrice As Double, ByVal itmQty As Integer)
        Name = itmName : Price = itmName : Quantity = itmQty
    End Sub
    Dim Name As String
    Dim Price As Double
    Dim Quantity As Integer
End Structure
Dim invItems As New List(Of InventoryItem)

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    invItems.Add(New InventoryItem("Hand Grenade", 10.99, 5))
    '' ... Add your additional items here


    For Each i As InventoryItem In invItems
        lstInventory.Items.Add(i.Name)
    Next

End Sub

Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
    Dim invItem As InventoryItem = invItems(lstInventoryItems.SelectedIndex)

    MessageBox.Show(invItem.Name & "," & invItem.Price & "," & invItem.Quantity)
End Sub

结束类

于 2013-05-02T04:56:03.457 回答