Mikem
Mikem

Reputation: 59

Returning string lines that only contain listbox items

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

Answers (3)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73462

I see several problems in your code.

  1. searchValList.Text has to be item.ToString();
  2. Inner while loop spins till EOF for fisrt iteration, in second Iteration it will always return null since EOF already reached.
  3. In all the else part inside the loop you're setting "The value was not found in this file" that is completely wrong

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

Tilak
Tilak

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

user123456
user123456

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

Related Questions