2

我想选择富文本框文本的最后一个“{”和“}”之间的文本。我有下一个代码,但我在“LastIndexOf”函数上有一个错误,我不知道如何修复它。有人可以给我一些帮助吗?

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

最后索引错误:

计数必须是正数,并且必须引用字符串、数组或集合中的某个位置。参数名称:计数

4

2 回答 2

1

似乎您已经超出了文本范围。当您获取子字符串或索引时,您始终应该使用字符串边界或子字符串边界。此外,您需要检查选择是否有效。

我会重写你的代码如下:

    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;
        }
    }
于 2014-03-19T13:35:32.023 回答
1

你 LastIndexOf 参数搞砸了,还有选择的长度,你需要减去起点才能得到正确的长度。

尝试一个更简单的版本:

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;
  }
}
于 2014-03-19T13:43:20.047 回答