简体   繁体   English

如何删除RichTextBox的内容并添加新内容?

[英]How do I delete the contents of a RichTextBox and add new contents?

How do I delete the contents of a RichTextBox and add new contents? 如何删除RichTextBox的内容并添加新内容?

I am retrieving multiple sections of data from a database. 我正在从数据库中检索数据的多个部分。 The RichTextBox displays the first section from the database. RichTextBox显示数据库的第一部分。

The customer hits the Next button ... the RichTextBox should display the second section from the database. 客户单击“下一步”按钮。RichTextBox应该显示数据库的第二部分。 The following code concatenates the second section to the first section. 以下代码将第二部分连接到第一部分。

gRTbx.Document.Blocks.Clear();

gobjParagaph.Inlines.Add(new Run(st));
gobjFlowDoc.Blocks.Add(gobjParagaph);
gRTbx.Document = gobjFlowDoc;

I also tried placing this before adding to the RichTextBox. 在添加到RichTextBox之前,我还尝试过放置它。

gobjFlowDoc.Blocks.Clear();

How do I remove the first section from the RichTextBox ... then display the second section? 如何从RichTextBox中删除第一部分...然后显示第二部分?

You need to replace your FlowDocument with a new one (or re-instantiate it). 您需要用一个新的FlowDocument替换它(或重新实例化它)。 Below is a simple example that puts text in the RichTextBox on a button click and then replaces it with different text the 2nd time the button is clicked. 下面是一个简单的示例,在单击按钮时将文本放入RichTextBox ,然后在第二次单击按钮时将其替换为其他文本。

  private int numTimes = 0;

  private void SimpleTest(object sender, RoutedEventArgs e)
  {
    if (numTimes == 0)
    {
      FlowDocument fd = new FlowDocument();
      Paragraph p = new Paragraph();
      p.Inlines.Add("This is the first bit of text.");
      fd.Blocks.Add(p);
      gRTbx.Document = fd;
      numTimes++;
    }
    else
    {
      FlowDocument fd = new FlowDocument();
      Paragraph p = new Paragraph();
      p.Inlines.Add("This is the second bit of text.");
      fd.Blocks.Add(p);
      gRTbx.Document = fd;
    }
  }

If you don't want to re-instantiate the FlowDocument you can just clear it out. 如果您不想重新实例化FlowDocument ,则可以清除它。 Just make sure that you clear it before you add the new Blocks to it: 只需确保清除它,然后Blocks其添加新Blocks

  private int numTimes = 0;
  private FlowDocument fd = new FlowDocument();
  private Paragraph p = new Paragraph();

  private void SimpleTest(object sender, RoutedEventArgs e)
  {
    if (numTimes == 0)
    {
      p.Inlines.Add("This is the first bit of text.");
      fd.Blocks.Add(p);
      gRTbx.Document = fd;
      numTimes++;
    }
    else
    {
      p.Inlines.Clear();
      fd.Blocks.Clear();
      p.Inlines.Add("This is the second bit of text.");
      fd.Blocks.Add(p);
      gRTbx.Document = fd;
    }
  }

Make sure to also clear out the Inlines in your Paragraph object. 请务必也很清楚了InlinesParagraph对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM