Tuesday, July 14, 2009

C# - How to scroll in RichTextBox control after searching?

To search a value in a TextRichBox control you can use .Find( ... ) method,
and if it can find a match then it returns the index of starting character.
To fit the text and show the found value, .ScrollToCaret() method do the job.
The sample code is as following:



...
int iIndx = this.rtbFileTxt.Find(strFind,
this.rtbFileTxt.SelectionStart,
RichTextBoxFinds.None);

if (iIndx < 0) return false;

this.SuspendLayout();
this.rtbFileTxt.SelectionStart = iIndx;
this.rtbFileTxt.SelectionColor = Color.Yellow;
this.rtbFileTxt.SelectionBackColor = Color.Black;

Point ptCharIndx =
this.rtbFileTxt.GetPositionFromCharIndex(this.rtbFileTxt.SelectionStart);
if (ptCharIndx.Y > this.rtbFileTxt.Height)
this.rtbFileTxt.ScrollToCaret();
this.ResumeLayout(true);
...

Share/Bookmark