例:假设有一个listBox,选定多个项目之后,按“删除”按钮批量删除选中项目。
以下是”删除”按钮的事件处理方法(.NET 2.0 程序)
private void deleteButton_Click(object sender, EventArgs e)
{
if (this.listBox.SelectedIndex != -1)
{
int count = this.listBox.SelectedIndices.Count;
//循环采用倒序,从最后一个开始删除,这样index就是正确的
for (int i = 0; i < count; i++)
{
int index = count - 1 - i;
int deleteIndex = this.listBox.SelectedIndices[index];
this.listBox.Items.RemoveAt(deleteIndex);
}
}
}
这样的方法适用于使用索引批量删除项目的情况,不仅限于ListBox。