aarnaut
aarnaut

Reputation: 557

Deleting an item in ListView from a file C#

How can I delete an item from a ListView, and also delete it from a file? Here is the code I currently have:

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");                  
    }

This deletes item from a list, but does not delete its file. It only deletes the file when I select multiple items. For example, I selected 3 items: 1.txt, 2.txt, 3.txt. It will only delete the file from the last one I selected, which is 3.txt, but will remove all 3 from the list.

Upvotes: 2

Views: 1165

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

You can materialize the items to be deleted into a list and then delete:

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");
  } 
}

Upvotes: 3

Related Questions