James Buttler
James Buttler

Reputation: 95

Adding strings to a RichTextBox in C#

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";

Upvotes: 4

Views: 73732

Answers (5)

Mike Hawk
Mike Hawk

Reputation: 41

I wrote this as a simple log-to-screen kinda thing to inform user of stuff going on in the background or to acknowledge various actions.

Add a RichTextBox on the form, here I call it "rtbLog"

Then call the below and add your message and any optional formatting you want. So for example:

DoWriteToLog("Hey, welcome!", true, Color.Green)


public void DoWriteToLog(string strLogMessage, bool blnHighlighted = false, Color myFontColor = default(Color), bool blnNewLine = true)
        {
            string dtStamp = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
            if (blnNewLine)
                strLogMessage = dtStamp + strLogMessage + Environment.NewLine;
            if (blnHighlighted)
            {                
                rtbLog.SelectionColor = myFontColor;             // Optional font color passed to method
                if (strLogMessage.ToLower().Contains("help"))       // IF there is 'help' in the message, highlight it blue
                    rtbLog.SelectionBackColor = Color.LightBlue;
                rtbLog.SelectionFont = new Font("Cambria", 10F, FontStyle.Bold, GraphicsUnit.Point);
                rtbLog.AppendText(strLogMessage);                
            }
            else            
                rtbLog.AppendText(strLogMessage);
            rtbLog.ScrollToCaret();
        }

The above DoWriteToLog statement will write "Hey, welcome!" to the RichTextBox in bold Green font. It adds a timestamp to each line entered as well, but you can avoid that by turning off blnNewLine. Of course it's specific to my use, but you can modify it to suit yours.

I also have a help 'detector' in there so if I am putting a help message on the screen it highlights it a specific color, you can comment/delete those two lines as needed.

Note the only required parameter, of course, is the message. This way, since I use this a lot, I don't have to add all the parameters every time thus, saving lots of typing :-)

Upvotes: 0

xyz
xyz

Reputation: 782

richTextBox2.Document.Blocks.Clear();
richTextBox2.Document.Blocks.Add(new Paragraph(new Run("string")));

Upvotes: 4

Roger Far
Roger Far

Reputation: 2385

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

Please don't use +

Upvotes: 10

agent-j
agent-j

Reputation: 27913

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

Upvotes: 19

abatishchev
abatishchev

Reputation: 100268

richTextBox2.Text = "Something " + richTextBox2.Text + " and something"

Upvotes: -1

Related Questions