linguini
linguini

Reputation: 1939

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???

Upvotes: 6

Views: 34397

Answers (3)

Habib
Habib

Reputation: 223187

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");
}

Upvotes: 12

Till
Till

Reputation: 3154

Wrong event i suppose. Move that code to the constructor of your form/control or attach it to an event of another control. Repopulating the listBox on SelectedIndexChanged when the initial state of the listbox is empty does not make sense.

Upvotes: 1

undefined
undefined

Reputation: 34238

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);
    }
}

Upvotes: 1

Related Questions