Richtext formatting...

lidds

Well-known member
Joined
Oct 19, 2004
Messages
122
Programming Experience
Beginner
I have a richtextbox and what I want to be able to do is to format each line, so one line would be say italic and another line would be bold.

I have done the following code which changes the second line to bold, however if you click the button again to write some more text to the richtextbox the formatting of the previous text is lost:

VB.NET:
    Private Sub btnClient_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClient.Click
        Dim line1 As String = "Client Says [" & Now().ToString & "]"
        Dim line2 As String = "[" & Now().ToString & "]" & " Simon - Hello how are you"

        Me.RichTextBox1.Text += line1 & vbNewLine
        textColour(line1, False)
        Me.RichTextBox1.Text += line2 & vbNewLine
        textColour(line2, True)

        Me.RichTextBox1.SelectionStart = Me.RichTextBox1.Text.Length

    End Sub

    Private Sub textColour(ByVal text As String, ByVal bold As Boolean)
        Dim newFont As Font
        RichTextBox1.SelectionStart = RichTextBox1.Find(text)

        If bold = True Then
            newFont = New Font(Me.cmbFont.Font, FontStyle.Bold)
        Else
            newFont = New Font(Me.cmbFont.Font, FontStyle.Regular)
        End If

        RichTextBox1.SelectionFont = newFont
    End Sub

I obviously need some help one keeping the format, basically I want to acheive the type of formating style that msn messenger has.

Thanks in advance

Simon
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,553
Location
Norway
Programming Experience
10+
Set the selection font before you add text:
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim line1 As String = String.Format("Client Says [{0}]", Date.Now.ToString)
    Dim line2 As String = String.Format("[{0}] Simon - Hello how are you", Date.Now.ToString)
    textColour(FontStyle.Bold)
    Me.RichTextBox1.AppendText(line1 & vbNewLine)
    textColour(FontStyle.Italic Or FontStyle.Underline)
    Me.RichTextBox1.AppendText(line2 & vbNewLine)
End Sub

Private Sub textColour(ByVal style As FontStyle)
    RichTextBox1.SelectionStart = Me.RichTextBox1.TextLength
    RichTextBox1.SelectionFont = New Font(Me.cmbFont.Font, style)
End Sub
+= operator is only used for numerical expressions, &= for adding strings.
 
Top Bottom