C# 如何删除列表框中的多个项目?

C# 如何删除列表框中的多个项目?,c#,listbox,C#,Listbox,如何从列表框中删除 同时删除多个索引 请注意,我正在使用汽车类型列表及其详细信息 列表框中的对象具有汽车类型成本率更新:如果要删除所有已注释的选定项目: foreach (int i in listBox1.SelectedIndices) listBox1.Items.RemoveAt(i); 如果要删除所有项目,请使用“清除”: 如果要在特定索引处删除,请使用RemoveAt: 或在循环中: for(int i = 0; i < listBox1.Items.Count; i

如何从列表框中删除

同时删除多个索引

请注意,我正在使用汽车类型列表及其详细信息 列表框中的对象具有汽车类型成本率更新:如果要删除所有已注释的选定项目:

foreach (int i in listBox1.SelectedIndices)
    listBox1.Items.RemoveAt(i);
如果要删除所有项目,请使用“清除”:

如果要在特定索引处删除,请使用RemoveAt:

或在循环中:

for(int i = 0; i < listBox1.Items.Count; i++)
    listBox1.Items.RemoveAt();
你必须使用循环

大概是这样的:

List<int> indexesToDelete = new List<int>();

// add items you want to remove to List like this:
indexesToDelete.Add(1);
indexesToDelete.Add(2);
indexesToDelete.Add(4);

// loop will execute code inside inside for all items added to list
foreach (int indexToDelete in indexesToDelete)
{
    listbox1.RemoveAt(indexToDelete);
}

编辑:itemsToDelete已重命名为IndexToDelete,请在代码中显示一些代码。

同意,如果不知道您已经尝试了什么,我们将无法帮助您。请尝试使用您的标题进行谷歌搜索。我将此代码用于int x=listBox1.SelectedIndices.Count-1;x>=0;x-{int idx=listBox1.SelectedIndices[x];listBox1.Items.AddlistBox1.Items[idx];listBox1.Items.RemoveAtix;}@user1548100:编辑了我的答案。要使用对象,必须使用Remove。或者,如果要将索引与RemoveAt一起使用,则需要使用for循环。@TimSchmelter我的代码有问题吗?我的列表只是索引列表,而不是项对象。我使用了数字索引。很抱歉,误解了代码,因为您将变量itemsToDelete命名为indexToDelete,而不是indexToDelete。请注意,您没有声明它,循环语法也不会编译。您是对的@TimSchmelter,我已经修复了这个问题。太多的PHP:
for(int i = 0; i < listBox1.Items.Count; i++)
    listBox1.Items.RemoveAt();
Car car = (Car) listBox1.Items[0];
listBox1.Items.Remove(car);
List<int> indexesToDelete = new List<int>();

// add items you want to remove to List like this:
indexesToDelete.Add(1);
indexesToDelete.Add(2);
indexesToDelete.Add(4);

// loop will execute code inside inside for all items added to list
foreach (int indexToDelete in indexesToDelete)
{
    listbox1.RemoveAt(indexToDelete);
}