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);
  }
}
Advertisement

One Response to Adding Formatted Text to RichTextBox

  1. Daniel says:

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

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.