C# 从列表框/列表中删除多个选定对象

C# 从列表框/列表中删除多个选定对象,c#,C#,这是我第一次使用这个网站,所以希望我能正确地问我的问题 我正在尝试制作一个程序,其中包含RentalCar对象的绑定列表。现在我试着让自己一次移除多辆车 这是我目前拥有的删除按钮的代码 private void buttonRemoveRental_Click(object sender, EventArgs e) { try { //List<RentalCar> tempList = n

这是我第一次使用这个网站,所以希望我能正确地问我的问题

我正在尝试制作一个程序,其中包含RentalCar对象的绑定列表。现在我试着让自己一次移除多辆车

这是我目前拥有的删除按钮的代码

        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");
        }
private void按钮删除租赁\u单击(对象发送者,事件参数e)
{
尝试
{
//List templast=new List();(这是我尝试的另一个解决方案)
int index=listboxrent.SelectedIndex;
对于(int i=rentalList_uu1;Count-1;i>=0;i--)
{
if(listBoxRental.SelectedDices.Contains(i))
{
租客搬迁(i);
}
}
}
捕获(例外)
{
MessageBox.Show(“请从列表中选择要删除的车辆”);
}
但有时列表框中会留下一个我无法删除的项目。每次我尝试删除最后一个项目时,它都会删除列表中的所有项目


我正在尝试的另一个解决方案是创建另一个列表,该列表将存储从我的rentalList中选择的车辆,然后循环并从rentalList中删除模板列表中的项目,但我不知道如何执行该操作,因为我正在存储对象。

当您循环并从同一列表中删除项目时,您正在删除错误的项目索引错误,因为删除项目后索引将重置

试试这个

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

对于(inti=0;i试试这个解决方案。它对我很有效

 private void buttonRemoveRental_Click(object sender, EventArgs e)
    {
       var selectedItems= listBoxRental.SelectedItems.Cast<String>().ToList();
       foreach (var item in selectedItems)
            listBoxRental.Items.Remove(item);
    }
private void按钮删除租赁\u单击(对象发送者,事件参数e)
{
var selectedItems=listboxrent.selectedItems.Cast().ToList();
foreach(selectedItems中的变量项)
listBoxRental.Items.Remove(项目);
}

什么类型的列表是
rentalList
?这是因为您使用了错误的迭代。当您移除(i)时,列表的内容正在更改,下一个移除(i)将被移动。rentalList是列表框的绑定列表。rentalList=new BindingList();listBoxRental.DataSource=rentalList_u2;;这很有效。除了我的程序还可以将车辆添加到列表之外,这意味着我无法添加任何车辆,因为旧列表不再绑定到listBox。我只需将.Cast更改为.Cast,并且我必须使用rentalList_2;移除(项)因为我有一个错误,说我无法更改列表框的数据或其他东西。但它现在可以工作了。谢谢。如果可以,我会投票支持它。但我还没有足够的声誉。你不需要投票支持,伙计。如果你觉得我的解决方案适合你的问题,你可以“接受”它作为答案。干杯