1

This is my first time using this site so hopefully I ask my question properly.

I am trying to make a program that has a BindingList of RentalCar objects. Now I am trying to allow myself to remove multiple cars at once.

This is the code i have currently for the remove button.

        private void buttonRemoveRental_Click(object sender, EventArgs e)

        {
        try

        {

            //List<RentalCar> tempList = new List<RentalCar>(); (This was here for another solution i am trying)

            int index = listBoxRental.SelectedIndex;
            for (int i = rentalList_.Count - 1; i >= 0; i--)
            {
                if (listBoxRental.SelectedIndices.Contains(i))
                {
                    rentalList_.RemoveAt(i);
                }

            }
        }
        catch(Exception)
        {
            MessageBox.Show("Please select a vehicle to remove from the list");
        }

But sometimes one item will be left in the listbox which i can't delete. And every single time if i try deleting the last item, it deletes every item from the list.

Another solution i am trying was to create another list, which will store the selected vehicles from my rentalList_ and then loop through and delete the items in the tempList from the rentalList_ But i don;t know how to go about that because i am storing objects.

4

2 に答える 2

1

When you loop and remove item from same List, you are removing wrong item at wrong index because index will be reset after you remove an item.

Try this

List<RentalCar> tempList = new List<RentalCar>();
for (int i = 0; i <=rentalList.Count - 1; i++)
{
    if (!listBoxRental.SelectedIndices.Contains(i))
    {
       tempList.Add(rentalList[i]);
    }
}

You can then bind tempList to ListBox

于 2013-01-16T03:16:51.787 に答える
1

Try this solution. It's working fine on me.

 private void buttonRemoveRental_Click(object sender, EventArgs e)
    {
       var selectedItems= listBoxRental.SelectedItems.Cast<String>().ToList();
       foreach (var item in selectedItems)
            listBoxRental.Items.Remove(item);
    }
于 2013-01-16T04:22:14.877 に答える