c# - 如何从列表框 C# 中删除选定的项目

我目前正在尝试查看用户在列表框中选择的所有文件和文件夹。目前,我可以使用 openfiledialogue 列出用户选择的内容,但是当我尝试从列表框中删除它时,我现在面临着问题。我试图让用户点击文件旁边的复选框,然后按删除按钮将其删除

这是删除按钮的代码

      private void button2_Click(object sender, EventArgs e)
    {
        for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
        {
            listView1.Items.Remove(listView1.SelectedItems[i]);
        }

    }

这是添加文件到列表框以备不时之需

    private void button1_Click(object sender, EventArgs e)
    {

        OpenFileDialog openfiledialog = new OpenFileDialog();
        // Display open file dialog
        openfiledialog.InitialDirectory = "C:\\";
        //openfiledialog.Multiselect = true;
        openfiledialog.Title = "Lock File";
        openfiledialog.Filter = "All Files | *.*";
        openfiledialog.ShowDialog();


        if (openfiledialog.FileName != "")
        {

        //move through FileInfo array and store in new array of fi
            listView1.Items.Clear();
            foreach (string file in openfiledialog.FileNames)
            {
                listView1.Items.Add(file);
            }        
        }

    }

然后我按下删除按钮没有任何反应,我在谷歌上看到了一些关于使用 selectionmode 的答案,但是当我使用它时,我的列表框没有 selectionmode 的属性并且有红线下划线

最佳答案

您的问题是因为 SelectedItems 属性实际上是对 Items 集合的引用,您在遍历集合时更改了集合。 试试下面的代码

listView1.BeginUpdate();
ArrayList vSelectedItems = new ArrayList(listView1.SelectedItems);
foreach (string item in vSelectedItems)
{
   listView1.Items.Remove(item);
}
listView1.EndUpdate();

BeginUpdate()EndUpdate() 方法将优化此操作的性能 - 在这些方法调用之间的事件期间,listView 不会自行刷新。

https://stackoverflow.com/questions/7102681/

相关文章:

css - 当类名只是一个整数时,如何编写 CSS 选择器?

php - 二进制 in_array 搜索

r - 安装 Rstem 包的问题

objective-c - 使用 NSRegularExpression 将每个匹配项替换为方法的结

wix - 在 WIX 安装程序中检查 RAM

php - 如何用PHP生成每月的天数?

sql - oracle如何获取最新的员工记录?

python - 在 PYTHON 中使用 POUND SIGN 作为字符串?

c# - 每 2 分钟运行一次任务计划程序

perl - 如何在 Perl 中创建一个新文件?