Reputation: 3205
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.
Upvotes: 5
Views: 37869
Reputation: 755557
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() + @" }";
}
}
Upvotes: 9
Reputation: 9012
You can use the Rtf property of your RichTextBox
. First generate an rtf string:
var rtf = string.Format(@"{{\rtf1\ansi \b {0}\b0 \line {1}\line\line }}",
tn.date.ToString("MM/dd/yy H:mm:ss"),
tn.text);
And append the string to the existing text in your RichTextBox
:
this.notes_pln.SelectionStart = this.notes_pln.TextLength;
this.notes_pln.SelectedRtf = rtf;
Upvotes: 4