Highlights Text in a Text File in C#
Submitted by donbermoy on Tuesday, November 3, 2015 - 20:10.
In this tutorial, I will teach you how to create a program load a text file in the richtextbox, search a particular word, and then highlights it.
So, now let's start this tutorial!
1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio 2010: Go to File, click New Project, and choose Windows Application.
2. Add two buttons; the open text file button and the search button, one textbox for the user to type and search a particular word, and a richtextbox to display the contents of the text file.
3. Now, have this code below.
Import first the namespace of IO to access the streamreaders for opening a text file.
Now in button1, we will have an openfiledialog that will trigger to open a text file. And after choosing a text file, it will load in the richtextbox.
Lastly, this code is for button2 that will trigger to highlights the searched word in the textbox.
Output:
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below.
Best Regards,
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Mobile: 09488225971
Landline: 826-9296
E-mail:[email protected]
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
- using System.IO;
- private void button1_Click(object sender, EventArgs e)
- {
- if (ofd.ShowDialog() == DialogResult.OK)
- {
- //get the filename of the text file
- string filename = ofd.FileName;
- //read all the contents
- string textfile = File.ReadAllText(filename);
- // display the contents in the richtextbox
- rtDisplay.Text = textfile;
- }
- }
- private void button2_Click(object sender, EventArgs e)
- {
- //string words = txtSearch.Text;
- //rtDisplay.Text = "";
- //rtDisplay.Text = words;
- int index = 0;
- // if the textbox has an inputted text
- while (index < rtDisplay.Text.LastIndexOf(txtSearch.Text)){
- //find text in the searched word
- rtDisplay.Find(txtSearch.Text,rtDisplay.TextLength, RichTextBoxFinds.None);
- // highlights the word with a color yellow
- rtDisplay.SelectionBackColor = Color.Yellow;
- // highlights all those words that is the same with the searched word in the textbox
- index = rtDisplay.Text.IndexOf(txtSearch.Text, index) + 1;
- }
- }
Add new comment
- 222 views