Adding strings to a RichTextBox in C#

64,608

Solution 1

richTextBox2.AppendText(Environment.NewLine + DateTime.Today + " Hello"); 

Solution 2

richTextBox2.AppendText(String.Format("{0} the date is {1}{2}", "Hello", DateTime.Today, Environment.NewLine));

Please don't use +

Solution 3

richTextBox2.Document.Blocks.Clear();
richTextBox2.Document.Blocks.Add(new Paragraph(new Run("string")));
Share:
64,608
James Buttler
Author by

James Buttler

Updated on July 06, 2020

Comments

  • James Buttler
    James Buttler almost 4 years

    I currently have a function that will set a value to a RichTextBox, although how could you "add" a value or a new line to it, rather than overwriting existing data in the RichTextBox?

    richTextBox2.Text = DateTime.Today + " Hello";
    
    • abatishchev
      abatishchev almost 13 years
      James, I recommend you to use a single OpenId to log in, so you will be the same user as usually
  • James Buttler
    James Buttler almost 13 years
    @abatishchev There is more than one function adding text to this, hence I don't think your solution would work
  • David Heffernan
    David Heffernan almost 13 years
    This is going to be horribly inefficient when there is a lot of text in the control
  • abatishchev
    abatishchev almost 13 years
    @David: Nothing said in the answer about a lot of text
  • David Heffernan
    David Heffernan almost 13 years
    reading the entire contents of the control just to add another line of text is very inefficient. Why go out of your way to write inefficient code?
  • abatishchev
    abatishchev almost 13 years
    @David: Does RichTextBox.Text property read entire control content rather than holds it into a variable? I didn't knew that.
  • David Heffernan
    David Heffernan almost 13 years
    It's just a wrapper around the Windows control I expect and the Windows control holds the text. The implementation of the Text getter will send a message to the control to retrieve the entire text, I'd guess.
  • schmijos
    schmijos about 11 years
    Why no "+"? Just for readability? Or is there an other reason?
  • 0xDEADBEEF
    0xDEADBEEF almost 9 years
    @JosuaSchmid strings are immutable. Using + to chain n of them (especially for big strings and/or many catenations) creates n-1 strings in memory one bigger than the last one, resulting in a (temporary) waste of memory and a lot of computing overhead. This is why using String.Format() and the StringBuilder-Class is prefered in favor of +
  • user1027167
    user1027167 about 7 years
    The user asked for winforms not for WPF.