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:
type text free in thextbox delete text , type new text on again , highlight text textbox in richtextbox in real time.
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
Post a Comment