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.
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");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.