【问题标题】:Insert a value in a specific line by index按索引在特定行中插入值
【发布时间】:2018-12-16 12:33:03
【问题描述】:
private void Parse_Click(object sender, EventArgs e)
{
    for (int i = 0; i < keywordRanks.Lines.Length; i++)
    {
        int p = keywordRanks.Lines.Length;
        MessageBox.Show(p.ToString());

        string splitString = keywordRanks.Lines[i];
        string[] s = splitString.Split(':');

        for (int j = 0; j < keywords.Lines.Length; j++)
        {
            string searchString = keywords.Lines[j];

            if (s[0].Equals(searchString))
            {
               richTextBox1.Lines[j] = searchString + ':' + s[1];
            }
        }
    }
}

我在特定行中插入字符串时遇到问题。我有 2 个多行文本框和一个 RichTextBox。
我的应用程序将逐行搜索从textbox1textbox2 的字符串,并且需要将这些匹配值插入到RichTextBox 控件中,但要插入到它在textbox2 中找到的确切索引位置。

如果在textbox2 的第 5 行找到值,则需要将找到的行插入 RichTextBox 第 5 行。
我的代码无法正常工作。我尝试了很多,但没有运气。我需要类似下面的代码,但它不起作用并且引发了IndexOutOfBound 异常。

richTextBox1.Lines[j] = searchString + ':' + s[1];

【问题讨论】:

  • 文本框控件的multiline属性是否设置为true且文本中出现换行符?
  • 是的多行属性为真。我的代码工作正常,直到它与 textbox2 中的行匹配(我用 message box 对其进行了测试),但是为了将找到的字符串插入到 Richtextbox 编辑器中,与在 textbox2 中找到它的索引相同。这里出现了错误。
  • 你会得到 IndexOutOfRangeException,因为你正在迭代 keywords.Lines.Length,但是在做 richTextBox1.Lines[j] ,它的行数可能比关键字少
  • 没有办法。即使我尝试了以下几行,它在消息框中重新调整了值,但没有插入不确定原因。 MessageBox.Show(richTextBox1.Lines[2]); richTextBox1.Lines[2].Insert(2, "123");
  • 你能提供一些示例输入吗?

标签: c# winforms richtextbox


【解决方案1】:

您的RichTextBox 必须包含所有需要的行,然后才能使用行索引设置值。
如果控件不包含文本或换行符 (\n),则不会定义任何行,并且任何设置特定 Line[Index] 值的尝试都将生成 IndexOutOfRangeException 异常。

在这里,我使用了一个预先构建的数组,大小为可能匹配的数量(keywords 文本框的Lines.Length)。找到的所有匹配项都存储在原始位置。然后将该数组分配给RichTextBox.Lines 属性。

注意:直接使用和预置RichTextBox.Lines 将无效:文本将保持为空。

string[] MatchesFound = new string[keywords.Lines.Length];
foreach (string currentSourceLine in keywordRanks.Lines)
{
    string[] SourceLineValue = currentSourceLine.Split(':');

    var match = keywords.Lines.ToList().FindIndex(s => s.Equals(SourceLineValue[0]));
    if (match > -1)
        MatchesFound[match] = currentSourceLine;
}
richTextBox1.Lines = MatchesFound;

     Source        Matches         Result
  (keywordRanks)  (keywords)    (RichTextBox)
  -------------------------------------------
     aand:1         aand           aand:1
     cnd:5          this one      
     cnds:9         cnds           cnds:9
     fan:2          another one   
     gst:0          cnd            cnd:5
                    fan            fan:2

【讨论】:

  • 非常感谢。我明天会检查这个。
猜你喜欢
  • 1970-01-01
  • 2014-12-03
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-17
相关资源
最近更新 更多