Ankul
Ankul

Reputation: 121

displaying all lines in list box from a file in WPF

I have this code which is suppose to display all lines which contains a specifies string but instead of returning all lines with that string it only returns last line which contains the string. How can I make it to display all lines?

if(bookingType == "Express")
        {
            string stringToSearch = @"Express";
            string[] lines = File.ReadAllLines(@"pathway");
            foreach (string line in lines)
            {
                if (line.Contains(stringToSearch))
                {
                    lstAvailableTrains.Items.Clear();
                    lstAvailableTrains.Items.Add(line);
                }
            }
        }

Upvotes: 0

Views: 152

Answers (2)

Clemens
Clemens

Reputation: 128146

Use LINQ, and set the ListBox's ItemsSource property:

using System.Linq;
...

lstAvailableTrains.ItemsSource =
    File.ReadAllLines("pathway").Where(line => line.Contains(stringToSearch));

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222722

You are clearing the items in each time.You need to move clear out of the loop

lstAvailableTrains.Items.Clear();
foreach (string line in lines)
{
  if (line.Contains(stringToSearch))
  {     
     lstAvailableTrains.Items.Add(line);
  }
}

Upvotes: 2

Related Questions