我想选择最后一个' {'和'}' richtextbox文本。 我有下一个代码,但我在" 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;
}
LastIndexOf错误:
计数必须是正数,并且必须指代其中的位置 字符串,数组或集合。参数名称:count
答案 0 :(得分: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;
}
}
答案 1 :(得分: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;
}
}