簡體   English   中英

在 c# 的富文本框中的指定行中添加文本

[英]Adding a text in a specified line of rich textbox in c#

如何在富文本框中的特殊行中添加文本...示例:我想將“此文本”添加到第 6 行

只要行號可用,您就可以使用

示例:

string[] lines = richTextBox1.Lines;
lines[6] = "This Text";
richTextBox1.Lines = lines;

我認為你可以使用.Lines屬性,它是一個字符串[],並且是可讀寫的...但我認為你必須在第6行前插入空行,如果它們不存在的話。

正如其他人所說,在Windows窗體中,您可以使用RichTextBox.Lines屬性執行此操作。

WPF RichTextBox這有點棘手:你需要為行的開頭獲取TextPointer ,將其向下移動7行然后返回一個位置,然后在那里插入文本。 像這樣的東西(我不在Visual Studio附近,這可能無法編譯!):

public static void InsertText(RichTextBox richText, int line, string text) {
    // Find the position at the end of the specified line.
    var documentStart = richText.Document.ContentStart;
    var lineEnd = documentStart.GetLineStartPosition(line + 1)
                      .GetPositionAtOffset(1, LogicalDirection.Backward);

    // Insert the text there.
    lineEnd.InsertTextInRun(text);
}

如果要在第6行插入文本而不丟失當前文本

string[] buffer = new string[richTextBox1.Lines.Length+1];
Array.Copy(richTextBox1.Lines, 0, buffer, 0, 5);
buffer[5] = "MyText";
Array.Copy(richTextBox1.Lines, 5, buffer, 6, richTextBox1.Lines.Length - 5);
richTextBox1.Lines = buffer;

一般來說:

string[] lines = richTextBox1.Lines;
lines[6] = "This Text";
richTextBox1.Lines = lines;

作品。 但是您需要在之前添加這些行,因此首先您必須啟動它們。 例如:

private void RTBoxSetLines(RichTextBox rtbox, int lines)
{
    while(lines > 0)    // here you may use type you like
    {
        rtbox.AppendText(System.Environment.NewLine);
        lines--;
    }
}

注意命令 rtbox.Clear(); 也將清除所有行,因此在清除所有行后,您必須再次聲明這些行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM