Resolved Problem with index using a class list to mirror a listbox

AronW

New member
Joined
May 30, 2022
Messages
2
Programming Experience
Beginner
Ive gotten error messsages that the selceted index is out of range, i have checked several times and it should not be. I want ot remove the selected index from both the listbox and the list. Can anyone help me?
Remove selected index:
        private void RemoveButton_Click(object sender, EventArgs e) 
        {
            if (CartListBox.SelectedIndex != -1)
            {
                var price = CartProduct[CartListBox.SelectedIndex].GetSetProPrice;
                CartListBox.Items.RemoveAt(CartListBox.SelectedIndex);
                CartProduct.RemoveAt(CartListBox.SelectedIndex); //outside index??
            }
        }
 
I'd guess control index change when you change the items, assign the control index to a variable first and use that variable as RemoveAt argument afterwards.
 
@JohnH is unto something. When you remove the selected item, the index of the selected item for the list will change. The recommendation to store the index into another variable and then use that for both removing from the listbox and list is the more robust solution.

The hacky solution would be to swap the order of lines 6 and 7. The hacky solution will work great until someone refactors the code and decides to swap the lines back the other way for symmetry reasons (e.g. In other parts of the code, item is added to the list first before adding to the list box, therefore for symmetry, remove from list box and then remove from the list.)

An even better solution would be to use WinForms binding so that all changes on the list reflect on the listbox and vice versa.
 
Why do you need separate lists in the first place? What data is stored in each? There's a good chance that you only need one list. You can then bind that list to the control to display one aspect of it.
 
@JohnH is unto something. When you remove the selected item, the index of the selected item for the list will change. The recommendation to store the index into another variable and then use that for both removing from the listbox and list is the more robust solution.

The hacky solution would be to swap the order of lines 6 and 7. The hacky solution will work great until someone refactors the code and decides to swap the lines back the other way for symmetry reasons (e.g. In other parts of the code, item is added to the list first before adding to the list box, therefore for symmetry, remove from list box and then remove from the list.)

An even better solution would be to use WinForms binding so that all changes on the list reflect on the listbox and vice versa.
Thx, this helped a lot!
 

Latest posts

Back
Top Bottom