How can I do when I search some word from textbox in richTextBox, scroll being top on the searching word?

Viewed 40
string[] words = textBox1.Text.Split(',');
            foreach (string word in words)
            {
                int startindex = 0;
                while (startindex < richTB1.TextLength)
                {
                    int wordstartIndex = richTB1.Find(word, startindex, RichTextBoxFinds.None);
                    if (wordstartIndex != -1)
                    {
                        richTB1.SelectionStart = wordstartIndex;
                        richTB1.SelectionLength = word.Length;
                        richTB1.SelectionBackColor = Color.GreenYellow;
                    }
                    else
                        break;
                    startindex += wordstartIndex + word.Length;
                }
            }
2 Answers

you need to use richTB1.ScrollToCaret() after changing the color of the selected word

In the example below,

Suppose textBox1.text="hello";

Click the search button each time, scroll button being top on the searching word

    int startindex = 0;
    private void Button1_Click(object sender, EventArgs e)
    {
        richTB1.SelectionBackColor = Color.Transparent;
        string word = textBox1.Text;
        int wordstartIndex = richTB1.Find(word, startindex, RichTextBoxFinds.None);
        if (wordstartIndex != -1)
        {
            richTB1.SelectionStart = wordstartIndex;
            richTB1.SelectionLength = word.Length;
            richTB1.SelectionBackColor = Color.GreenYellow;
            richTB1.ScrollToCaret();
            startindex += wordstartIndex + word.Length;
        }
        if (startindex >= richTB1.TextLength)
        {
            startindex = 0;
        }
    }

Try this extension

will Highlight a word in index line

 //richTextBox : your Control 
// word want to be Highlighted 
// index of Line 
// Color : Highlight  color 

 public static void HighlightWord(this RichTextBox   richTextBox, string word, int index, Color color)
    {
        richTextBox.SelectAll();
        richTextBox.SelectionBackColor = Color.White; 
        var lines = richTextBox.Lines;
        var start = richTextBox.GetFirstCharIndexFromLine(index);
        if (index < 0 || index >= lines.Length || start < 0)
            return;
        // Get the 1st char index of the appended text
        int indexword = lines[index].IndexOf(word);    
        var length = word.Length;//lines[index].Length;
        richTextBox.Select(start + indexword, length);               
        richTextBox.SelectionBackColor = color;
    }
Related