James Buttler
James Buttler

Reputation: 95

How to add contents on directory into a ListBox in C#

I am trying to grab the contents of a directory and display each one, on a seperate row of ListBox, the code I have so far is:

private void button10_Click(object sender, EventArgs e)
{
    string[] filePaths = Directory.GetFiles(@"folder");
    foreach (string path in filePaths)
    {
        listBox2.Items.AddRange(path + Environment.NewLine);
    }
}

Upvotes: 1

Views: 1585

Answers (4)

user744186
user744186

Reputation:

You should use Add,not AddRange.

Upvotes: 1

Sebastiano Merlino
Sebastiano Merlino

Reputation: 1283

I can suggest to you this answer: How to implement glob in C#

Upvotes: 0

Akram Shahda
Akram Shahda

Reputation: 14781

Use the following:

listBox2.Items.Add(path);

Or the following:

string[] filePaths = Directory.GetFiles(@"folder");
listBox2.Items.AddRange(filePaths);

Upvotes: 0

Thomas Levesque
Thomas Levesque

Reputation: 292695

Your code is almost correct; use Add instead of AddRange, and remove the Environment.NewLine.

There are other possible approaches:

  • AddRange is used to add multiple items at once. So you could do that instead of the loop:

    listBox2.Items.AddRange(filePaths);
    
  • You could also use data binding:

    listBox2.DataSource = filePaths;
    

Upvotes: 0

Related Questions