How to add a bold text in Rich TextBox programatically using VB.NET

c#, richtextbox, vb.net

Solution

When using a `RichTextBox`, why not just use RTF?

Example:

Sub Main
    Dim f = new Form()
    Dim print_text = new RichTextBox() With {.Dock = DockStyle.Fill}
    f.Controls.Add(print_text)

    Dim sb = new System.Text.StringBuilder()
    sb.Append("{\rtf1\ansi")
    sb.Append("This number is bold: \b 123\b0 ! Yes, it is...")
    sb.Append("}")
    print_text.Rtf = sb.ToString()

    f.ShowDialog()
End Sub

Result:

MSDN

This way, you can also easily wrap the RTF stuff into extension methods:

Module RtfExtensions

    <Extension()>
    Public Function ToRtf(s As String) As String
        Return "{\rtf1\ansi" + s + "}"
    End Function

    <Extension()>
    Public Function ToBold(s As String) As String
        Return String.Format("\b {0}\b0 ", s)
    End Function

End Module

and use it like

Dim text = "This number is bold: " + "123".ToBold() + "! Yes, it is..."
print_text.Rtf = text.ToRtf()

Problem

I have this code: ``` print_text.Text = "Patient number: " + ds.Tables("patients").Rows(0).Item(0) print_text.AppendText(Environment.NewLine) print_text.Text = print_text.Text + "Last name: " + ds.Tables("patients").Rows(0).Item(1) print_text.AppendText(Environment.NewLine) ``` Now the above data i am adding programatically and it works fine. However in the above code i want to add `Patient number` and `Last name` in bold font.

Original source