从 C# 中的 Richtextbox 中选择文本 [英] Select text from a Richtextbox in C#

查看:52
本文介绍了从 C# 中的 Richtextbox 中选择文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 错误:

LastIndexOf Error:

计数必须为正,并且必须引用字符串、数组或集合.参数名称:计数

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

推荐答案

你的LastIndexOf参数搞乱了,还有选择的Length,需要减去起点才能得到合适的长度.

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.

尝试更简单的版本:

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

这篇关于从 C# 中的 Richtextbox 中选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆