ttom
ttom

Reputation: 1065

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?

I am retrieving multiple sections of data from a database. The RichTextBox displays the first section from the database.

The customer hits the Next button ... the RichTextBox should display the second section from the database. 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.

gobjFlowDoc.Blocks.Clear();

How do I remove the first section from the RichTextBox ... then display the second section?

Upvotes: 0

Views: 791

Answers (1)

Stewbob
Stewbob

Reputation: 16899

You need to replace your FlowDocument with a new one (or re-instantiate it). 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.

  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. Just make sure that you clear it before you add the new Blocks to it:

  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.

Upvotes: 1

Related Questions