C# GUI highlight text

Exercise: Write a simple GUI program to highlight the matched text in a RichTextBox. Your program will display one TextBox and one RightTextBox. The text to search is input in the TextBox. Then this text is searched in the text in the RichTextBox. If the text in the RichtTextBox contains the text to find, it will be highlighted.

 

Csharp exercises: search text and highlight the matched text

Solution: To run the code solution for this exercise, you will need to create a project(Window Form Applications) in Visual Studio. The controls to be placed on your form are TextBox and richTextBox.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace WindowsFormsApplication2

{

    public partial class Form1 : Form

    {

        int start;

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            richTextBox1.ReadOnly = true;//read only Richtextbox

            textBox1.TabIndex = 0;//focus the textbox           

            clearBox(); //reset the text

        }

 

        private void textBox1_TextChanged(object sender, EventArgs e)

        {

            clearBox(); //reset highlighting process

            string In_text = richTextBox1.Text;

            while (start < In_text.Length)

            {

                if (In_text.IndexOf(textBox1.Text, start) >= 0) //highlight the text matched

                {

                    richTextBox1.SelectionStart = In_text.IndexOf(textBox1.Text,start);//start position of highlighting

                    richTextBox1.SelectionLength = textBox1.Text.Length;//length of text to highlight

                    richTextBox1.SelectionColor = Color.Fuchsia;//color used in highlighting the text matched

                }

                start = start + 1; //move to next text that may match

 

            }

 

        }

 

        private void clearBox()

        {

            richTextBox1.Clear();

            richTextBox1.Text = "C# programming, C, C++, VB,Visual Studio, tutorials, exercises.C# programming, \nC, C++, VB,Visual Studio, tutorials, exercises.\nC, C++, VB,Visual Studio, tutorials, exercises.";

            start = 0;

        }

    }

}





Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.