【问题标题】:Deleting an item in ListView from a file C#从文件 C# 中删除 ListView 中的项目
【发布时间】:2015-01-20 09:41:06
【问题描述】:

如何从 ListView 中删除项目,同时从文件中删除它? 这是我目前拥有的代码:

private void button3_Click(object sender, EventArgs e)
    {
        listView1.Items.Remove(listView1.SelectedItems[0]);

        foreach (ListViewItem item in listView1.SelectedItems)
                File.Delete(path + "//Lyrics//" + item.Text + ".txt");                  
    }

这会从列表中删除项目,但不会删除其文件。当我选择多个项目时,它只会删除文件。例如,我选择了 3 个项目:1.txt、2.txt、3.txt。它只会删除我选择的最后一个文件,即 3.txt,但会从列表中删除所有 3 个文件。

【问题讨论】:

  • 先从光盘中删除,再从列表中删除,因为被选中的项可能会因为您删除而变为空!
  • 非常感谢!!这么简单的解决方案..至少我不会再犯这些愚蠢的错误了。

标签: c# listview


【解决方案1】:

您可以将要删除的项目具体化到一个列表中然后删除:

private void button3_Click(object sender, EventArgs e) {
  var toDelete = listView1.SelectedItems.ToList();

  foreach(var item in toDelete) {
    listView1.Items.Remove(item);
    File.Delete(path + "//Lyrics//" + item.Text + ".txt");
  } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多