使用listbox访问2D数组VB

时间:2013-05-01 21:20:43

标签: arrays vb.net

所以我试图使用列表框来访问我的2D数组中的变量。我不确定这样做的最佳方式是什么。现在我正在使用列表框的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

1 个答案:

答案 0 :(得分: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

结束班