VinceCat
VinceCat

Reputation: 25

Using listbox to access 2D array VB

So I am trying to use a listbox to access variables in my 2D array. I am unsure what is the best way to do this. Right now I am using the selectedindex of the listbox to access it but I am only seeing the second dimension being show in my message box. Any help would be appreciated.

    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

Upvotes: 0

Views: 1068

Answers (1)

Serialize
Serialize

Reputation: 491

You don't want to use a multi-dimensional array here.

The OOP way to do this would be to define inventory item as its own class or structure, and use instances to both populate your list box and store the inventory item price and quantity.

Something like:

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

End Class

Upvotes: 1

Related Questions