2012-10-08 22 views
5

ho questo codice:Come aggiungere un testo in grassetto in Rich TextBox programatically usando VB.NET

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) 

Ora i dati di cui sopra sto aggiungendo programatically e funziona benissimo. Tuttavia nel codice precedente voglio aggiungere Patient number e Last name in carattere in grassetto.

risposta

9

Quando si utilizza un RichTextBox, perché non basta usare RTF?


Esempio:

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 

Risultato:

RichTextBox with bold text

MSDN


In questo modo, si può anche facilmente avvolgere la roba RTF in metodi di estensione:

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 

e utilizzarlo come

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

Soluzione carina e ordinata, mi piace. – Raffaeu

3

Utilizzare la proprietà RichTextBox.SelectionFont.
controllare questi collegamenti MSDN su come fare questo: Link 1 e Link 2

Speranza che aiuta.
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 
+0

Questo è per un testo selezionato. Quello che voglio è che i dati che sto aggiungendo dinamicamente alla ricca Textbox dovrebbero essere in carattere grassetto –

+0

Non è dinamico o statico. Puoi usare questa proprietà in qualsiasi posto, ma dovrai usarla in modo appropriato. Ho aggiornato la mia risposta per includere un semplice esempio. Per favore guarda. Grazie. – Luftwaffe

+0

Bello, fammi provare ... grazie per l'aiuto :) –

Problemi correlati