I am developing a Windows Form application. I use RichTextBox.LoadFile
method to load text from a file and highlight some portion of the text. The text in the file contains return characters.
Suppose that I want to highlight the highlight
. First I find the startIndex
and the length
of the the highlight
part, then use RichTextBox.Select(startIndex, length)
and give some color to it.
When I use SubString
method, I can find the correct text. But when I apply the same value of startIndex
and length
to Select
method, the highlighted part becomes [space][space][space]the highli
. It looks the Select
method takes some return characters into account and cause some problem.
How can I resolve it?
I think you should use the Find()
method of RichTextBox
:
int nextStartIndex;
public void Find(string keyword){
int i = richTextBox1.Find(keyword, nextStartIndex, RichTextBoxFinds.None);
if(i != -1) {
nextStartIndex = i + keyword.Length;
}
}
first time i hear about it and i use the richTextBox
a lot. try to use SubString
to find the substring you want on the richTextBox.Text
instead of the string from the file. if you are already do it try to check the return number from substring method and see if it reference the right location.
also, please share your code please, i want to see it for myself. if it is a .net problem then i need to go over my work...
This is how I "Search" for a specific text in a RichTextBox then highlight it to RED
private void ColoritRed(RichTextBox rtb, string StringToHighlight)
{
int pos = 0;
string searchText = StringToHighlight;
pos = rtb.Find(searchText);
while (pos != -1)
{
if (rtb.SelectedText == searchText)
{
this.ActiveControl = rtb;
rtb.SelectionStart = pos;
rtb.SelectionLength = searchText.Length;
rtb.SelectionColor = Color.Red;
}
pos = rtb.Find(searchText, pos + 1, RichTextBoxFinds.MatchCase);
}