1

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);
    }
}
James Buttler
  • 95
  • 1
  • 1
  • 5
  • OK, fine. Do you have a question? – SLaks Jun 26 '11 at 19:25
  • 1
    You should name your controls. – SLaks Jun 26 '11 at 19:25
  • Note to my answer.You are iterating through the collection.Every path is a single item so you need to call Add(path),not AddRange() which adds an array to the list items.You could use AddRange for the string[] filePaths array. –  Jun 26 '11 at 19:27

4 Answers4

1

You should use Add,not AddRange.

Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
0

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;
    
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

Use the following:

listBox2.Items.Add(path);

Or the following:

string[] filePaths = Directory.GetFiles(@"folder");
listBox2.Items.AddRange(filePaths);
Akram Shahda
  • 14,655
  • 4
  • 45
  • 65
0

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

Community
  • 1
  • 1
Sebastiano Merlino
  • 1,273
  • 12
  • 23