Reputation: 121
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
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
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