Reputation: 59
I am trying to retrieve lines of data from a text file that contain items I added to a listbox, but it just keeps returning all lines of data from my test file:
foreach (var item in searchValList.Items)
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(searchValList.Text))
{
sb.AppendLine(line.ToString());
resultsTextBox.Text = sb.ToString();
}
else
{
resultsTextBox.Text = "The value was not found in this file";
}
}
}
Upvotes: 0
Views: 111
Reputation: 73462
I see several problems in your code.
searchValList.Text
has to be item.ToString();
EOF
for fisrt iteration, in second Iteration it will always return null since EOF
already reached.It should be something like this.
string[] lines = File.ReadAllLines("...");
var listboxItems = searchValList.Cast<object>().Select(x=> x.ToString()).ToList();
foreach (var line in lines)
{
if (listboxItems.Any(x=> line.Contains(x)))
{
sb.AppendLine(line);
}
}
if(sb.Length > 0)
{
resultsTextBox.Text = sb.ToString();
}
else
{
resultsTextBox.Text = "The value was not found in this file";
}
Upvotes: 0
Reputation: 30698
You are searching for the same value in all the lines, (and virtually your outer loop is meaningless)
Change following
if (line.Contains(searchValList.Text))
to
if (item.Text != null && line.Contains(item.Text.ToString()))
Upvotes: 2
Reputation: 2659
I think it should be this way since you have a listbox. Try this :
foreach (var item in searchValList.Items)
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(item.ToString()))
{
sb.AppendLine(line.ToString());
resultsTextBox.Text = sb.ToString();
}
else
{
resultsTextBox.Text = "The value was not found in this file";
}
}
}
Upvotes: 0