清除数据后在 RichTextBox 中显示数据时出错

Error when displaying data in RichTextBox after clearing it

我的 GUI 上有一个 RichTextBox,我有两个按钮,一个用于显示数据,一个用于清除数据。在显示按钮上,我使用此例程将一些数据显示到 RichTextBox 中:

Block firstBlock = richTextBox_Console.Document.Blocks.FirstOrDefault();
richTextBox_Console.Document.Blocks.InsertBefore(firstBlock, new Paragraph(new Run("MyFirstLine= " + MyVariable + "\n" )));

string message;
for (int i = 0; i < 6; i++)
{
    message = "";
    message += "Line:" + (i + 1).ToString() + "\n";
    richTextBox_Console.Document.Blocks.InsertBefore(firstBlock, new Paragraph(new Run(message)));
}

然后点击 CLEAR,我会 this:

richTextBox_Console.SelectAll();
richTextBox_Console.Selection.Text = "";

现在,当我再次单击“显示”按钮时,在线:

richTextBox_Console.Document.Blocks.InsertBefore(firstBlock, new Paragraph(new Run("MyFirstLine= " + MyVariable + "\n" )));

firstBlocknull 所以该行抛出这个错误:

value can not be null. Parameter name: nextSibling

知道发生了什么事吗?第一次显示数据很好,然后就不行了。

我也尝试过 richTextBox_Console.Document.Blocks.Clear(); 清除,但我仍然遇到同样的错误。

在您的代码之前添加这一行

if(!richTextBox_Console.Document.Blocks.Any())richTextBox_Console.Document.Blocks.Add(new Paragraph());

它会检查你的文本中是否有任何块,如果没有 - 它会为你添加一个段落。

还有,你最好把FirstOrDefault()改成First(),这样下次你就知道问题是你没有paragraphs/sections

您可以像这样实现删除按钮的事件处理程序:

richTextBox_Console.Document.Blocks.Clear();
richTextBox_Console.Document.Blocks.Add(new Paragraph());