JonnyAppleseed
JonnyAppleseed

Reputation: 51

Filling Combo/ListBox with file names from a directory

I'm attempting to populate a ListBox with file names from a directory. My code works, however, when I recompile the program the items are no longer there. Also when I click on an item in the ListBox the content of the ListBox is duplicated over and over. Any guidance would be much appreciated, thanks.

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
    FileInfo[] files = dir.GetFiles("*.txt");
    foreach ( FileInfo file in files )
    {
        listBox1.Items.Add(file);
    }
}

Upvotes: 0

Views: 98

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39956

You've populated your ListBox in the incorrect event. So each time you select an item, the ListBox is populated again. You should put it in another event like Button_Click or Form_load:

private void Form1_Load(object sender, EventArgs e)
{
    DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
    FileInfo[] files = dir.GetFiles("*.txt");
    foreach ( FileInfo file in files )
    {
        listBox1.Items.Add(file);
    }
}

//Or in a Button_Click event
private void button1_Click(object sender, EventArgs e)
{
    DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
    ....
}

Upvotes: 4

JonnyAppleseed
JonnyAppleseed

Reputation: 51

So thanks to the advice of @S.Akbari my solution to my issue is below.

      public Form1()
    {
        InitializeComponent();
             DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
        FileInfo[] files = dir.GetFiles("*.txt");
        foreach (FileInfo file in files)
        {
            listBox1.Items.Add(file);
        }

    }

Upvotes: 0

Related Questions