How to delete from directory selected files in listbox

Ant6729

Well-known member
Joined
Jan 22, 2019
Messages
56
Programming Experience
Beginner
Hello, everyone!

I have a simple code

C#:
        private void button7_Click(object sender, EventArgs e) // ??????? ???????????? ?????????? ???????? ?????? ?? ????????
        {
            ListBox.SelectedObjectCollection selectedItems = new ListBox.SelectedObjectCollection(listBox1);
            selectedItems = listBox1.SelectedItems;


            if (listBox1.SelectedIndex != -1)
            {
                for (int i = selectedItems.Count - 1; i >= 0; i--)
                    listBox1.Items.Remove(selectedItems[i]);
            }
        }

And I need not only remove selected items from listbox, but to delete them from directory, they belong to also

Could you show me in code how its possible to do?
 
I said that you need to remove items from the data source rather than the control. What's that data source? You're setting it yourself:
                List<FileInfo> files;


                using (var fbd = new FolderBrowserDialog())
                {
                    if (fbd.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    files = Directory.GetFiles(fbd.SelectedPath).Select(f => new FileInfo(f)).ToList();
                }


                listBox1.DataSource = files;
                listBox1.DisplayMember = "Name";
                listBox1.ValueMember = "FullName";

That List<FileInfo> is the data source so that's what you need to remove items from.

Also, given that each item is a FileInfo, you can use that to delete the corresponding file. The FileInfo class has a Delete method so you can call that to delete. There's no way to delete multiple files with a single method call other than to write your own method that takes multiple files and deletes them one by one. As I have already said and should not have to say again, you need to either delete the file before removing the corresponding item or else you need to save information about that file to a variable and then use that variable after removing the item. That should be common sense because it's nothing specific to do with programming. If I gave you a list of anything that had had an item removed, would you then be able to get that item from the list to use it for something? Of course not, because it's no longer in the list to get it. Don't turn your brain off just because you['re programming. The rules of life and the world still apply.
 
Back
Top Bottom