【问题标题】:How can I search in a richTextBox text for a text not a single word/string?如何在richTextBox 文本中搜索不是单个单词/字符串的文本?
【发布时间】:2016-06-22 01:21:20
【问题描述】:

如果在 textBox1 中输入例如:Form1 然后我会得到很多结果,它会用黄色突出显示这个结果。

但是当我复制粘贴到 textBox1 时,一些文本不仅是 Form1,例如:

if ((null != _FileProcessingWorker) && (_FileProcessingWorker.IsBusy))
{
    _FileProcessingWorker.CancelAsync();
}

然后它不会将其着色为黄色。由于某种原因,它仅适用于单个单词/字符串,但不适用于文本块。

void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
    {
        richTextBox1.Text = File.ReadAllText(
            ListViewCostumControl.lvnf.Items[
                ListViewCostumControl.lvnf.SelectedIndices[0]
            ].Text);

        int start = richTextBox1.SelectionStart;
        int startIndex = 0;
        int index = 0;
        string word = textBox1.Text;
        Color selectionColor = richTextBox1.SelectionColor;

        while ((index = richTextBox1.Text.IndexOf(word, startIndex)) != -1)
        {
            richTextBox1.Select(index, word.Length);
            richTextBox1.SelectionColor = Color.Yellow;
            startIndex = index + word.Length;
        }

        richTextBox1.SelectionStart = start;
        richTextBox1.SelectionLength = 0;
        richTextBox1.SelectionColor = selectionColor;
    }
}

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    您面临的问题是由您的 RichTextBox 的一个功能引起的。在控件中加载文本时,它会将回车换行符 ("\r\n") 组合转换为换行符。然而,文本框保持行尾不变。

    您可以通过复制轻松验证

    第一行
    第二行

    在 TextBox 和 RichtTextBox 中,然后检查它们的 Text 属性:

    最简单的解决方案是将 textBox1 中的“\r\n”字符替换为“\n”,以便它们与 RichTextBox 中使用的行尾匹配:

    string word = textBox1.Text;
    Color selectionColor = richTextBox1.SelectionColor;
    
    // match line-endings
    word = textBox1.Text.Replace("\r\n", "\n");
    
    while ((index = richTextBox1.Text.IndexOf(word, startIndex)) != -1)
    {
    // your other code
    }
    

    |

    【讨论】:

      猜你喜欢
      • 2016-06-04
      • 1970-01-01
      • 2018-06-18
      • 2022-12-22
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      相关资源
      最近更新 更多