Adding strings to a RichTextBox in C#

前端 未结 5 1844
独厮守ぢ
独厮守ぢ 2021-01-06 12:51

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

相关标签:
5条回答
  • 2021-01-06 13:26
    richTextBox2.AppendText(String.Format("{0} the date is {1}{2}", "Hello", DateTime.Today, Environment.NewLine));
    

    Please don't use +

    0 讨论(0)
  • 2021-01-06 13:26
    richTextBox2.Text = "Something " + richTextBox2.Text + " and something"
    
    0 讨论(0)
  • 2021-01-06 13:29

    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 :-)

    0 讨论(0)
  • 2021-01-06 13:48
    richTextBox2.AppendText(Environment.NewLine + DateTime.Today + " Hello"); 
    
    0 讨论(0)
  • 2021-01-06 13:48
    richTextBox2.Document.Blocks.Clear();
    richTextBox2.Document.Blocks.Add(new Paragraph(new Run("string")));
    
    0 讨论(0)
提交回复
热议问题