Hi all i have writen a bit of code here to read a line of text from a text file and display it depending on what the user searches for which is taken from a text box.

but it will only read one line it will not display all the records that have the word input from the text box what am missing.

private void btnSearch_Click(object sender, EventArgs e)
        {
            {
                string searchText = (txtSearchBirthMonth.Text);
                string file = @"C:\Users\michael\Documents\data.txt ";//path to text file 
                StreamReader reader = new StreamReader(file); string line = null;
                foreach (string record in reader.ReadLine().Split('|'))
                {
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (Regex.IsMatch(line, searchText, RegexOptions.IgnoreCase))
                        {
                            rtbRecord.Text = line;
                        }
                    }
                }
            }
        }

I see two potential issues with your code:

// first call to ReadLine() advances the stream
foreach (string record in reader.ReadLine().Split('|'))
{
  // first time will read the second line because of first call
  while ((line = reader.ReadLine()) != null)
  {
    if (Regex.IsMatch(line, searchText, RegexOptions.IgnoreCase))
    {
      // the text here will be overwritten on each pass, try += instead
      rtbRecord.Text = line;
    }
  }
}

Thanks that help and worked

public string GrepLineFromFile(string path, string pattern)
{
    if (File.Exists(path))
    {
        foreach (string line in File.ReadAllLines(path))
        {
            if (line.Contains(pattern))
            {
                return (line); 
            }
        }
    }
    else
    {
        Console.WriteLine("..file does not exist");
    }

    return (string.Empty);
}
commented: You should try to help people arrive at the answer, not just hand-feed them code without explanation -1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.