Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate files into a listbox from a folder in C# windows forms

I'm a newbie in C# and I have 2 Listboxes l-->istBox1 and listBox2 and I want to load files from folder into these listboxes. 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 is not displaying???

like image 910
linguini Avatar asked May 09 '12 12:05

linguini


2 Answers

Instead of listBox1_SelectedIndexChanged, update the listbox against some button click, otherwise your code looks fine. Initially you probably don't have any item in your listbox and that's why SelectedIndexChanged doesn't get fired when you click on it.

Edit: (Since the question has been edited, I will update my answer)
To pouplate your listboxes with Files, you should do that, in some event other than SelectedIndexChanged. Because at the start of your application your listboxes are empty and SelectedIndexChanged event gets fired when there are items in the listbox and user click on it. You may 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 may call this function with your listbox in some event against a button click or form load. e.g.

private void Form1_Load(object sender, EventArgs e)
{
    PopulateListBox(listbox1, @"C:\TestLoadFiles", "*.rtld");
    PopulateListBox(listbox2, @"C:\TestLoadFiles", "*.other");
}
like image 93
Habib Avatar answered Nov 09 '22 17:11

Habib


This might 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);
    }
}
like image 20
Not loved Avatar answered Nov 09 '22 17:11

Not loved