gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:19:21 25 4
gpt4 key购买 nike

我目前正在尝试查看用户在列表框中选择的所有文件和文件夹。目前,我可以使用 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 不会自行刷新。

关于c# - 如何从列表框 C# 中删除选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7102681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com