Click here to Skip to main content
15,888,020 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So i got my list of files from a folder, using a CheckedListBox,

How do i delete those checked items?


Thanks.

What I have tried:

private void bunifuFlatButton4_Click(object sender, EventArgs e)
{
    foreach (var item in checkedListBox1.CheckedItems)
    {
        string deletefiles = checkedListBox1.CheckedItems.ToString();
        File.Delete(deletefiles);
    }

}
Posted
Updated 26-Mar-21 16:32pm

1 solution

Set a breakpoint on the foreach line and use the debugger and look at the value of deleteFiles. It does not contain what you think it does.

Your logic is completely screwed up. Why are you calling ToString on CheckedItems? That's the very collection you're iterating over in the foreach. That's pointless. You're completely ignoring the iterator you setup over the collection, item.

Item is going to hold each checked item in the CheckedItems collection, allowing you to deal with one item in the collection at a time. You should be calling .ToString() on item. So long as it's holding the string representing a filepath, you should be passing that to File.Delete().
C#
private void bunifuFlatButton4_Click(object sender, EventArgs e)
{
    foreach (var item in checkedListBox1.CheckedItems)
    {
        string filepath = item.ToString();
        File.Delete(filepath);
    }
}

Learn to use the debugger. It's there to show you what the code is doing. Chances are really high that you think the code is doing something and it's actually doing something else.

The debugger is there to debug YOU and your understanding of the code.
 
Share this answer
 
Comments
Member 15121692 27-Mar-21 8:16am    
Thanks for your awnser, but it's not deleting the file in the folder.

This is my Load Function
{
string path = @"C:\Test";
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(path);
System.IO.FileSystemInfo[] files = di.GetFiles();
checkedListBox1.Items.AddRange(files);

}
Dave Kreskowiak 27-Mar-21 19:10pm    
OK, you're not adding filenames, or filepaths, to the CheckedListBox. You're adding FileInfo objects. Calling .ToString() on one of these returns the filename of the file the object is holding data on.

FileInfo objects hold other information, like FullName, which contains the fully qualified path to the file, not just the filename.

You should be using the FullName property to get the full path to the file and deleting that instead.
private void bunifuFlatButton4_Click(object sender, EventArgs e)
{
    foreach (FileInfo file in checkedListBox1.CheckedItems)
    {
        File.Delete(file.FullName);
    }
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900