按索引在特定行中插入值

时间:2018-12-16 12:33:03

标签: c# winforms richtextbox

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个多行TextBoxes和1个RichTextBox。
我的应用程序将逐行搜索从textbox1textbox2的字符串,并需要将这些匹配的值插入RichTextBox控件中,但要插入在textbox2中的确切索引位置。 / p>

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

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

1 个答案:

答案 0 :(得分:0)

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

在这里,我使用的是预先构建的数组,其大小与可能的匹配项的数量(Lines.Length文本框的keywords)相同。找到的所有匹配项都存储在此处的原始位置。然后将该数组分配给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