c# - Why when using a textBox to search for text and color the results the program freeze? -


i have class:

private class utility         {             public static void highlighttext(richtextbox myrtb, string word, color color)             {                 int s_start = myrtb.selectionstart, startindex = 0, index;                  while ((index = myrtb.text.indexof(word, startindex)) != -1)                 {                     myrtb.select(index, word.length);                     myrtb.selectioncolor = color;                      startindex = index + word.length;                 }                  myrtb.selectionstart = s_start;                 myrtb.selectionlength = 0;                 myrtb.selectioncolor = color.black;             }         } 

then using it:

private void textbox1_textchanged(object sender, eventargs e)         {             utility.highlighttext(richtextbox1, textbox1.text, color.red);         } 

first time when click in textbox color text in richtextbox. when delete text in textbox , it's empty program freeze , used breakpoint seems stuck in while loop in utility class in highlighttext.

what want is:

  1. type text free in thextbox delete text , type new text on again , highlight text textbox in richtextbox in real time.

  2. only when type words in textbox highlight/color in richtextbox. if type example word share highlight/color places contain or start letter s.

you need take account case word highlight empty, in case, want skip loop. otherwise, loop indefinitely, because startindex never increments, because keep adding 0 (word.length).

so add condition around loop so:

public static void highlighttext(richtextbox myrtb, string word, color color) {     int s_start = myrtb.selectionstart, startindex = 0, index;      if (!string.isnullorempty(word)) {         while ((index = myrtb.text.indexof(word, startindex)) != -1)         {             myrtb.select(index, word.length);             myrtb.selectioncolor = color;              startindex = index + word.length;         }     }      myrtb.selectionstart = s_start;     myrtb.selectionlength = 0;     myrtb.selectioncolor = color.black; } 

edit: should add when word empty, myrtf.text.indexof(word, startindex) method call return value of startindex. never return -1. more reason skip loop in case.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -