Search code examples
c#visual-studiocode-behind

Find and show multiple Line from specific text in richtextbox


Based from this thread How to get the line of specific text in richtextbox I want to ask another question about line of specific text in richtextbox.

From that thread, he wanted to show which line 'orange' text on? But, i want to know if he had another 'orange' like

Exmaple image

From that table, i want to show the line number of 'Orange' text i expected the output will be "Line 1,2,3,4"

Thank you very much.


Solution

  • You have to use a loop and keep track of the index you found the string last in. Something like this should work:

    private void button1_Click(object sender, EventArgs e)
    {
        string orange = "orange";
        var index = 0;
        do
        {
            index = richTextBox1.Find(orange, index, RichTextBoxFinds.None);
    
            if (index >= 0)
            {
                textBox1.Text += richTextBox1.GetLineFromCharIndex(index).ToString() + " ";
                index++;
            }
        } while (index >= 0);
    }
    

    This will find multiple instances of the string "orange" in different lines.