Inconsistent behaviour between in RichTextBox.Select with SubString method

强颜欢笑 提交于 2019-12-10 19:41:06

问题


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?


回答1:


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;          
   }
}



回答2:


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...




回答3:


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);
        }


来源:https://stackoverflow.com/questions/18248176/inconsistent-behaviour-between-in-richtextbox-select-with-substring-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!