Search code examples
c#winforms

How to add items to listbox if not exist?


I'm having an issue with my code, I'm trying to add items from a Directory to a ListBox, the issue is that I keep getting the same items (duplicated) over and over again.

here is my code:

String[] filesDir = Directory.GetFiles(@"C:\FOLDER");
foreach (string file in filesDir)
  if (!this.listbox1.Items.Contains(file))
  {
    listbox1.Items.Add(Path.GetFileNameWithoutExtension(file ) + @"  found");
  }

Solution

  • The string you are checking to see if it exists in the ListBox is different from the string being added.

    The modification of the code is as follows:

    String[] filesDir = Directory.GetFiles(@"C:\FOLDER");
    foreach (string file in filesDir)
    {
        var NewLineText = Path.GetFileNameWithoutExtension(file) + @"  found";
        if (!this.listBox1.Items.Contains(NewLineText))
            listBox1.Items.Add(NewLineText);
    }