Delete selected item from two list boxes

2019-09-09 06:31发布

问题:

I have a system where once a button is clicked a food item is added to Listbox1 and its price is added to Listbox2. I'm trying to create a button where the user can delete the food item and its price will be deleted.

I'm very new to this but I gave it a go at trying to achieve this task with my code below. The item deletes fine but the first price in the list is deleted, not the price of the item. This is a problem when there are multiple items. The program also crashes if there are no prices

If anyone could help that would be great, cheers

 Dim itemdel As Integer

    itemdel = ListBox1.SelectedValue

    ListBox2.Items.RemoveAt(itemdel)

    ListBox1.Items.Remove(ListBox1.SelectedItem)

回答1:

Presumably both of these values exist at the same index within their relative ListBox. Given that you can just calculate the index and remove both by index

Dim index As Integer = ListBox1.SelectedIndex
ListBox1.Items.RemoveAt(index)
ListBox2.Items.RemoveAt(index)