Adding Formatted Text to RichTextBox

RichTextBox provides the method AppendText() inherited from TextBoxBase to programmatically add  text to the editor control, but there seems to be no native method to append formatted text.

A small extension class adds this functionality:

public static class RichTextBoxExtensions
{
  const string NewLine = "\r\n";

  public static void AppendLine(this RichTextBox ed)
  {
    ed.AppendText(NewLine);
  }

  public static void AppendLine(this RichTextBox ed, string s)
  {
    ed.AppendText(s + NewLine);
  }

  public static void AppendBoldLine(this RichTextBox ed, string s)
  {
    int ss = ed.SelectionStart;
    ed.AppendText(s);
    int sl = ed.SelectionStart - ss + 1;

    Font bold = new Font(ed.Font, FontStyle.Bold);
    ed.Select(ss, sl);
    ed.SelectionFont = bold;
    ed.AppendText(NewLine);
  }
}

2 Responses to Adding Formatted Text to RichTextBox

  1. Daniel says:

    Thank you very much!. Very very useful!!!

  2. Scott says:

    Thanks! This helped a lot.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: