简体   繁体   中英

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

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.

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:

带有粗体文本的RichTextBox

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()

Use the RichTextBox.SelectionFont Property.
Check these MSDN Links on how to do this: Link 1 and Link 2

Hope it helps.
EDIT:

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim len As Integer
    RichTextBox1.Text = "Patient number: " + " 12345"
    RichTextBox1.SelectionStart = 0
    RichTextBox1.SelectionLength = "Patient number".Length
    RichTextBox1.SelectionFont = New Font("Arial", 12, FontStyle.Bold)
    RichTextBox1.SelectionLength = 0
    RichTextBox1.AppendText(Environment.NewLine)
    len = RichTextBox1.Text.Length
    RichTextBox1.AppendText("Last name: " + " ABCD")
    RichTextBox1.SelectionStart = len
    RichTextBox1.SelectionLength = "Last name".Length
    RichTextBox1.SelectionFont = New Font("Arial", 12, FontStyle.Bold)
    RichTextBox1.SelectionLength = 0
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM