how to deselect all in RichTextBox before selecting newly found text?

1.5k Views Asked by At

I have following function which selects and highlights text.

if (startIndex >= 0)
            {

                FormsRtb.SelectionBackColor = Color.CornflowerBlue;
                var selectedTextLength = findContext.TextToFind.Length;

                FormsRtb.Select(startIndex, selectedTextLength);
                _previoslyFoundTextIndex = startIndex + selectedTextLength;
            }

EveryTime new text is found I need to deselect and unhighlight previously found text.

I tried to do this code snippet before selecting new text, but id did not help.

Do you have any idea how to do this?

    FormsRtb.SelectAll();
    FormsRtb.SelectionBackColor = Color.White;
    FormsRtb.DeselectAll();
1

There are 1 best solutions below

0
On BEST ANSWER

Well, I think you are doing the selection itself not quite right: After

0) de-highlighting you should

1) set the SelctionStart and the SelectionLength then

2) set the SelectionBackColor.

You should not change the SelectionBackColor of the RTB itself (ie without setting the selection first) all the time..!

if (startIndex >= 0)
{
    FormsRtb.SelectAll();                    // first we un-highlight
    FormsRtb.SelectionBackColor = Color.White;   // probably FormsRtb.BackColor is better?
    FormsRtb.DeselectAll();

    var selectedTextLength = findContext.TextToFind.Length;

    FormsRtb.Select(startIndex, selectedTextLength);     // now we select..
    FormsRtb.SelectionBackColor = Color.CornflowerBlue;  //..and only then we highlight

    _previoslyFoundTextIndex = startIndex + selectedTextLength;
}