Question

I want to select the text that is between the last '{' and '}' of a richtextbox text. I have the next code, but I have an error on the "LastIndexOf" function and I don't know how to fix it. Can someone give me some help?

    private void highlightText()
    {
        mRtbxOperations.SelectionStart = mRtbxOperations.Text.LastIndexOf(@"{", 1, mRtbxOperations.SelectionStart);
        mRtbxOperations.SelectionLength = mRtbxOperations.Text.IndexOf(@"}", mRtbxOperations.SelectionStart, mRtbxOperations.Text.Length - 1);
        mRtbxOperations.SelectionBackColor = Color.LightBlue;
        mRtbxOperations.SelectionFont = new Font(mRtbxOperations.SelectionFont, FontStyle.Underline);
        mRtbxOperations.SelectionLength = 0;
    }

LastIndexOf Error:

The count must be positive and must refer to a location within the string, array or collection. Parameter name: count

Was it helpful?

Solution

You LastIndexOf parameters are messed up, as well as the Length of the selection, where you need to substract the starting point in order to get the proper length.

Try a simpler version:

int textStart = mRtbxOperations.Text.LastIndexOf(@"{",
                                                 mRtbxOperations.SelectionStart);
if (textStart > -1) {
  int textEnd = mRtbxOperations.Text.IndexOf(@"}", textStart);
  if (textEnd > -1) {
    mRtbxOperations.Select(textStart, textEnd - textStart + 1);
    mRtbxOperations.SelectionBackColor = Color.LightBlue;
  }
}

OTHER TIPS

Seems that you're getting out of the text bounds. When you are getting a substring or an index, you always should use the string bounds, or a substring bounds. Also, you need to check that the selection is valid.

I would rewrite your code as follows:

    private void highlightText()
    {
        Selection selection = GetSelection(mRtbxOperations.Text);
        if (selection == null)
            return;
        mRtbxOperations.SelectionStart = selection.Start;
        mRtbxOperations.SelectionLength = selection.Length;
        mRtbxOperations.SelectionBackColor = Color.LightBlue;
        mRtbxOperations.SelectionFont = new Font(mRtbxOperations.SelectionFont,   
            FontStyle.Underline);
    }

    private static Selection GetSelection(string text)
    {
        int sIndex = text.LastIndexOf(@"{");
        if (sIndex == -1)
            return null;
        int eIndex = text.IndexOf(@"}", sIndex);
        if (eIndex == -1)
            return null;

        return new Selection(sIndex + 1, eIndex);
    }

    public class Selection
    {
        public int Start { get; set; }
        public int End { get; set; }

        public int Length
        {
            get
            {
                return End - Start;
            }
        }

        public Selection(int startIndex, int endIndex)
        {
            this.Start = startIndex;
            this.End = endIndex;
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top