Fill files into a list from a folder in C # window forms

I am new to C # and I have 2 Listboxes l -> istBox1 and listBox2, and I want to upload files from a folder to these lists. I tried like this: listBox1:

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestLoadFiles"); FileInfo[] Files = dinfo.GetFiles("*.rtdl"); foreach (FileInfo file in Files) { listbox1.Items.Add(file.Name); } } 

listBox2:

 private void listBox2_SelectedIndexChanged(object sender, EventArgs e) { DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestLoadFiles"); FileInfo[] Files = dinfo.GetFiles("*.dlz"); foreach (FileInfo file in Files) { listbox2.Items.Add(file.Name); } } 

when I run the form, the files from the folder are not displayed.

+6
source share
3 answers

Instead of listBox1_SelectedIndexChanged, update the list by clicking the mouse button, otherwise your code will look normal. Initially, you probably do not have an item in your list, and that why SelectedIndexChanged does not start when you click on it.

Edit: (Since the question has been edited, I will update my answer)
To unzip your lists using files, you have to do this, in some cases, except SelectedIndexChanged. Since your lists are not filled at the beginning of your application, and the SelectedIndexChanged event is fired when there are elements in the list, and the user clicks on it. You can create the following function

 private void PopulateListBox(ListBox lsb, string Folder, string FileType) { DirectoryInfo dinfo = new DirectoryInfo(Folder); FileInfo[] Files = dinfo.GetFiles(FileType); foreach (FileInfo file in Files) { lsb.Items.Add(file.Name); } } 

Now you can call this function with your list in any event by clicking a button or loading a form. eg.

 private void Form1_Load(object sender, EventArgs e) { PopulateListBox(listbox1, @"C:\TestLoadFiles", "*.rtld"); PopulateListBox(listbox2, @"C:\TestLoadFiles", "*.other"); } 
+11
source

This may work;)

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { DirectoryInfo dinfo = new DirectoryInfo(@"C:\TestLoadFiles"); FileInfo[] Files = dinfo.GetFiles("*.rtdl"); foreach (FileInfo file in Files) { listbox2.Items.Add(file.Name); } } 
+1
source

Incorrect event, I suppose. Move this code to the constructor of your form / control or attach it to the event of another control. Re-placing the listBox in SelectedIndexChanged when the initial state of the list is empty does not make sense.

+1
source

Source: https://habr.com/ru/post/915285/


All Articles