Highlights Text in a Text File in C#

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. design 3. Now, have this code below. Import first the namespace of IO to access the streamreaders for opening a text file.
  1. using System.IO;
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.
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  4. OpenFileDialog ofd = new OpenFileDialog();
  6. if (ofd.ShowDialog() == DialogResult.OK)
  7. {
  8. //get the filename of the text file
  9. string filename = ofd.FileName;
  10. //read all the contents
  11. string textfile = File.ReadAllText(filename);
  12. // display the contents in the richtextbox
  13. rtDisplay.Text = textfile;
  14. }
  16. }
Lastly, this code is for button2 that will trigger to highlights the searched word in the textbox.
  1. private void button2_Click(object sender, EventArgs e)
  2. {
  3. //string words = txtSearch.Text;
  4. //rtDisplay.Text = "";
  5. //rtDisplay.Text = words;
  6. int index = 0;
  8. // if the textbox has an inputted text
  9. while (index < rtDisplay.Text.LastIndexOf(txtSearch.Text)){
  10. //find text in the searched word
  11. rtDisplay.Find(txtSearch.Text,rtDisplay.TextLength, RichTextBoxFinds.None);
  12. // highlights the word with a color yellow
  13. rtDisplay.SelectionBackColor = Color.Yellow;
  15. // highlights all those words that is the same with the searched word in the textbox
  16. index = rtDisplay.Text.IndexOf(txtSearch.Text, index) + 1;
  17. }
  19. }
Output: 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

Add new comment