Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add bold text to rich text box

Tags:

c#

winforms

I'm working with Visual Studio Express 2012 with C#.

I am using code to add text to a RichTextBox. Each time there are 2 lines added. The first line needs to be bold and the second line normal.

Here is the only thing I could think to try, even though I was sure it would not work:

this.notes_pnl.Font = new Font(this.notes_pnl.Font, FontStyle.Bold);
this.notes_pnl.Text += tn.date.ToString("MM/dd/yy H:mm:ss")  + Environment.NewLine;
this.notes_pnl.Font = new Font(this.notes_pnl.Font, FontStyle.Regular);
this.notes_pnl.Text += tn.text + Environment.NewLine + Environment.NewLine;

How can I add bolded lines to a rich text box?

Thanks for the answers submitted so far. I think I need to clarify a little. I am not adding these 2 lines 1 time. I will be adding the lines several times.

like image 839
Lee Loftiss Avatar asked Jan 19 '14 00:01

Lee Loftiss


1 Answers

In order to make the text bold you just need to surround the text with \b and use the Rtf member.

this.notes_pln.Rtf = @"{\rtf1\ansi this word is \b bold \b0 }";

OP mentioned that they will be adding lines over time. If that is the case then this could be abstracted away into a class

class RtfBuilder { 
  StringBuilder _builder = new StringBuilder();

  public void AppendBold(string text) { 
    _builder.Append(@"\b ");
    _builder.Append(text);
    _builder.Append(@"\b0 ");
  }

  public void Append(string text) { 
    _builder.Append(text);
  }

  public void AppendLine(string text) { 
    _builder.Append(text);
    _builder.Append(@"\line");
  }

  public string ToRtf() { 
    return @"{\rtf1\ansi " + _builder.ToString() + @" }";
  }
}
like image 139
JaredPar Avatar answered Nov 07 '22 02:11

JaredPar