DotNetCurry Logo

Search and Highlight Text in a RichTextBox

Posted by: Suprotim Agarwal , on 4/26/2008, in Category WinForms & WinRT
Views: 158951
Abstract: The RichTextBox is a Windows Form control that provides the user with the functionality to enter, edit and perform some advanced formatting features on the text. Besides its other uses, the RichTextBox also allows us to search and highlight text, which is the focus of this article. In this article, we will attempt to replicate the Find and FindNext functions found in text editors.
Search and Highlight Text in a RichTextBox
 
The RichTextBox is a Windows Form control that provides the user with the functionality to enter, edit and perform some advanced formatting features on the text. Besides its other uses, the RichTextBox also allows us to search and highlight text, which is the focus of this article. In this article, we will attempt to replicate the Find and FindNext functions found in text editors.
The Find() method of the RichTextBox comes with 7 overloaded methods. You can find the description for each one of them over here using the MSDN documentation. In this article, we will be using the last one of the overloads, that is the Find(String, Int32, Int32, RichTextBoxFinds).
Find(String, Int32, Int32, RichTextBoxFinds) - Searches the text in a RichTextBox control for a string within a range of text within the control and with specific options applied to the search.
The Find method of the RichTextBox control searches for text specified in the string parameter. If the text is found, it returns the first character position of the search string in the RichTextBox. If the text is not found, the Find() returns -1. If you specify the same value for the start position and the end position, the Find method searches the entire text, starting from the zero position.
Let us see some code:
Step 1: Create a new Windows Forms application. Drag and drop a RichTextBox(rtb) control, a textbox(txtSearch) and a button(btnFind) control to the form. The textbox will be used to enter the search string and on the button click, we will be performing a search in the RichTextBox. Add a class level variable called ‘start’. This variable will be the start position within the control's text from where you need to begin searching. Also add another variable called ‘indexOfSearchText’ to hold the position/index of the search string in the RichTextBox.
C#
      int start = 0;
      int indexOfSearchText = 0;
VB.NET
      Dim start AsInteger = 0
      Dim indexOfSearchText AsInteger = 0
Step 2: In the button click event, add the following code. The FindMyText() function, which we will visit in Step 3, is called by passing the search string, the start and the end index. If the string is found in the RichTextBox, the position of the search string is returned and highlighted. The function has been marked with appropriate comments to help you understand the code.
C#
        privatevoid btnFind_Click(object sender, EventArgs e)
        {
            int startindex = 0;
 
            if(txtSearch.Text.Length > 0)
                startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);
 
            // If string was found in the RichTextBox, highlight it
            if (startindex >= 0)
            {
                // Set the highlight color as red
                rtb.SelectionColor = Color.Red;
                // Find the end index. End Index = number of characters in textbox
                int endindex = txtSearch.Text.Length;
                // Highlight the search string
                rtb.Select(startindex, endindex);
                // mark the start position after the position of
                // last search string
                start = startindex + endindex;
            }
        }
VB.NET
            PrivateSub btnFind_Click(ByVal sender AsObject, ByVal e As EventArgs)
                  Dim startindex AsInteger = 0
 
                  If txtSearch.Text.Length > 0 Then
                        startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length)
                  EndIf
 
                  ' If string was found in the RichTextBox, highlight it
                  If startindex >= 0 Then
                        ' Set the highlight color as red
                        rtb.SelectionColor = Color.Red
                        ' Find the end index. End Index = number of characters in textbox
                        Dim endindex AsInteger = txtSearch.Text.Length
                        ' Highlight the search string
                        rtb.Select(startindex, endindex)
                        ' mark the start position after the position of
                        ' last search string
                        start = startindex + endindex
                  EndIf
            EndSub
Step 3: Now let us add the functionality to the FindNext() function. The function accepts the search string, and the start and end index. The search happens within the index specified. The validation occurs first where the start and end index are checked for valid values. We then use the Find() function of the RichTextBox to find the position of the search string in the RichtTextBox. If the string is found, the position of the string within the RichTextBox is returned. If the string is not found, -1 is returned. The function has been marked with appropriate comments to help you understand the code.
C#
       publicint FindMyText(string txtToSearch, int searchStart, int searchEnd)
        {
            // Unselect the previously searched string
            if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
            {
                rtb.Undo();
            }
 
            // Set the return value to -1 by default.
            int retVal = -1;
 
            // A valid starting index should be specified.
            // if indexOfSearchText = -1, the end of search
            if (searchStart >= 0 && indexOfSearchText >=0)
            {
                // A valid ending index
                if (searchEnd > searchStart || searchEnd == -1)
                {
                    // Find the position of search string in RichTextBox
                    indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
                    // Determine whether the text was found in richTextBox1.
                    if (indexOfSearchText != -1)
                    {
                        // Return the index to the specified search text.
                        retVal = indexOfSearchText;
                    }
                }
            }
            return retVal;
        }
VB.NET
         PublicFunction FindMyText(ByVal txtToSearch AsString, ByVal searchStart AsInteger, ByVal searchEnd AsInteger) AsInteger
                  ' Unselect the previously searched string
                  If searchStart > 0 AndAlso searchEnd > 0 AndAlso indexOfSearchText >= 0 Then
                        rtb.Undo()
                  EndIf
 
                  ' Set the return value to -1 by default.
                  Dim retVal AsInteger = -1
 
                  ' A valid starting index should be specified.
                  ' if indexOfSearchText = -1, the end of search
                  If searchStart >= 0 AndAlso indexOfSearchText >=0 Then
                        ' A valid ending index
                        If searchEnd > searchStart OrElse searchEnd = -1 Then
                              ' Find the position of search string in RichTextBox
                              indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None)
                              ' Determine whether the text was found in richTextBox1.
                              If indexOfSearchText <> -1 Then
                                    ' Return the index to the specified search text.
                                    retVal = indexOfSearchText
                              EndIf
                        EndIf
                  EndIf
                  Return retVal
         EndFunction
 
Step 4: If a user changes the search string in the textbox, you can handle the TextChanged event to reset the value of ‘start’ and ‘indexOfSearchText’ to zero. This starts the new search from the beginning.
C#
        // Reset the richtextbox when user changes the search string
        privatevoid textBox1_TextChanged(object sender, EventArgs e)
        {
            start = 0;
            indexOfSearchText = 0;
        }
VB.NET
            ' Reset the richtextbox when user changes the search string
            PrivateSub textBox1_TextChanged(ByVal sender AsObject, ByVal e As EventArgs)
                  start = 0
                  indexOfSearchText = 0
            EndSub
That’s it. Run the code and see your implementation of search and highlight in the RichTextBox. I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.
 
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by pradeep on Thursday, July 3, 2008 8:45 AM
very good
Comment posted by samdoss on Tuesday, September 23, 2008 8:48 AM
Drag and Drop from Listbox to Richtextbox

//Add two lines in Constructor
InitializeComponent();
this.richtextbox1.DragEnter += new System.Windows.Forms.DragEventHandler(this.richtextbox1_DragEnter);

this.richtextbox1.DragDrop += new System.Windows.Forms.DragEventHandler(this.richtextbox1_DragDrop);


Then

Event


private void Listbox1_MouseDown(object sender, MouseEventArgs e)
{
Listbox1.Refresh();
Listbox1.DoDragDrop(Listbox1.SelectedItem, DragDropEffects.Copy);
richtextbox1.DoDragDrop(Listbox1.SelectedItem, DragDropEffects.Copy);
}

private void richtextbox1_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
int i;
String s;

// Get start position to drop the text.
i = richtextbox1.SelectionStart;
s = richtextbox1.Text.Substring(i);
//richtextbox1.Text = richtextbox1.Text.Substring(0, i);
//// Drop the text on to the RichTextBox.
//richtextbox1.Text = richtextbox1.Text + e.Data.GetData(DataFormats.Text).ToString();
//richtextbox1.Text = richtextbox1.Text + s;
}

private void richtextbox1_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}

private void lstItemsFC_MouseDown(object sender, MouseEventArgs e)
{
lstItemsFC.Refresh();
lstItemsFC.DoDragDrop(lstItemsFC.SelectedItem, DragDropEffects.Copy);
richtextbox1.DoDragDrop(lstItemsFC.SelectedItem, DragDropEffects.Copy);
}


By,

Samdoss (Software Developer)
Comment posted by Suprotim Agarwal on Tuesday, September 23, 2008 10:50 PM
Samdoss: Thanks for the tip. In fact you could have written this article for us and we would have published it on dotnetcurry.

http://www.dotnetcurry.com/WriteForUs.aspx
Comment posted by Kypreos on Thursday, April 23, 2009 10:05 PM
How would you modify the code to search upwords?
Comment posted by M Yakub Mizan on Sunday, October 18, 2009 2:02 AM
Thanks I Find It Helpful :)
Comment posted by Andrew on Monday, November 16, 2009 9:03 PM
Thanks for the post! How would you highlight more than one match at the same time?
Comment posted by Jair on Monday, April 26, 2010 4:44 PM
Bien men, excelente
Comment posted by Gokila on Wednesday, August 4, 2010 12:52 AM
hello,
i want a different program with richtextbox, listbox, buttons, scrollbars using vb.net...
Comment posted by Chris on Thursday, October 7, 2010 11:05 AM
Great job.... Works nicely, and helps out huge!
Comment posted by matsolof on Sunday, October 24, 2010 4:21 PM
Great tutorial with very good comments and, above all, code that works!
Comment posted by Kris on Friday, October 29, 2010 9:12 AM
Hi just to make this a bit more user frendly it would be handy to add the following

rtb.ScrollToCaret();

as the last line in the button click routine, this would then ensure that if the text being searched was off screen the Rich text box would scroll to that part of the text to display it.
Comment posted by Paolo on Saturday, October 30, 2010 4:51 AM
Kris very nice tip thanks.
Comment posted by thanhtured on Saturday, December 11, 2010 5:03 AM
thanks!
Comment posted by Raj Mukut on Saturday, April 9, 2011 5:03 AM
Hi
Thanks for provoiding the best solution
Comment posted by Nick on Wednesday, April 13, 2011 2:23 PM
Very nice work. I implemented in contextmenustrip using a text box on a winform. Worked out nicely; contextmenustrip does not have a button to fire enter event, So i throw in another textbox and made it look like a button and fired search in CLick event!
Comment posted by Nick on Wednesday, April 13, 2011 3:15 PM
What if there are multiple occurances of the same string? the code only finds first occurance..
Comment posted by hareesh on Monday, February 13, 2012 11:22 PM
good artical
Comment posted by Deoraj Lalchan-Vine on Friday, March 16, 2012 7:08 PM
I wish someone could help me to put this functionality in an MS Access DB
Thanks
Comment posted by Zeeshanef on Monday, March 19, 2012 6:02 AM
Very good and informative.
It can also be done in standard for like this:

If startindex >= 0 Then
            ' Set the highlight color as red
            'rtb.SelectionColor = Color.Red
            ' Find the end index. End Index = number of characters in textbox
            Dim endindex As Integer = txtSearch.Text.Length
            ' Highlight the search string
            rtb.Select(startindex, endindex)
            ' mark the start position after the position of
            ' last search string
            start = startindex + endindex
            rtb.Focus() 'Adding focus instead red color
End if
Comment posted by Mahmut on Thursday, May 31, 2012 4:13 AM
Thank you, very good.
Comment posted by nagaraj on Wednesday, June 13, 2012 2:03 AM
can we retain footnotes in richtext box. kindly reply asap
Comment posted by Jean on Friday, July 27, 2012 2:50 AM
Maybe in btnFind_Click after rtb.Select(startindex, endindex)

      rtb.ScrollToCaret()
Comment posted by Compliler on Thursday, August 16, 2012 11:01 AM
Use this code to highlight all matches inside of rich text control:
Also you can count or store the position of each match to jump over each word highlighted.

            Dim strStringToSearch as string = txtSearch.Text
            start = 0
            indexOfSearchText = 0
            startindex = 0
            Do
                startindex = FindMyText(strStringToSearch, start, rtb.Text.Length)
                ' If string was found in the RichTextBox, highlight it
                If startindex >= 0 Then
                    ' Set the highlight color as red
                    rtbContent.SelectionBackColor = Color.Yellow
                    rtbContent.SelectionColor = Color.Red
                    ' Find the end index. End Index = number of characters in textbox
                    Dim endindex As Integer = strStringToSearch.Length
                    ' Highlight the search string
                    rtb.Select(startindex, endindex)
                    rtb.ScrollToCaret()
                    ' mark the start position after the position of
                    ' last search string
                    start = startindex + endindex
                    Application.DoEvents()
                    Refresh()
                End If
            Loop Until startindex < 0

Comment posted by ali rajabi on Wednesday, December 26, 2012 6:34 AM
thank you very mach .
i am from in iran.
Comment posted by akilan on Sunday, January 6, 2013 11:36 PM
Thank you, it is working well
Comment posted by vishal on Friday, March 8, 2013 6:08 AM
thank you so much sir...it's work and it's helpful for me...
Comment posted by Arvind Gupta on Friday, March 28, 2014 1:25 AM
Anyone have a idea how to do this in asp.net just replace the control richtextbox with multiline textbox.