Question Programaticaly add text to richtextbox with font formats

wiremilitia

New member
Joined
Oct 23, 2010
Messages
2
Programming Experience
5-10
I am trying to add formatted text to a rich text box...

For instance, I want to add a heading as bold ("HEADING: ") and some data after it as regular ("REGULAR Data")...

I'd like to have a couple functions to perform the action.

When I use the below functions to add txt to a single rtf box, I get lines in either all bold or all regular. It doesn't seem to keep the font formatting after it adds text..

Public Function AddRegtxt(ByVal RTC As RichTextBox, ByVal Txt2Send As String)
With RTC
.SelectionStart = Len(.Text)
.Text &= Txt2Send
.SelectionStart = (Len(.Text)) - (Len(Txt2Send))
.SelectionLength = Len(Txt2Send)
.SelectionFont = New Font(RTC.SelectionFont, FontStyle.Regular)
.SelectionFont = New Font("Default Sans Serif", 10, FontStyle.Regular)
End With
End Function
Public Function AddBoldtxt(ByVal RTC As RichTextBox, ByVal Txt2Send As String)
With RTC
.SelectionStart = Len(.Text)
.Text &= Txt2Send
.SelectionStart = (Len(.Text)) - (Len(Txt2Send))
.SelectionLength = Len(Txt2Send)
.SelectionFont = New Font(RTC.SelectionFont, FontStyle.Bold)
.SelectionFont = New Font("Default Sans Serif", 10, FontStyle.Bold)
End With
End Function



What ever happened to the vb6 "mkbold" option??
Can I use the vb6 RTF control in VB.NET?
 
You can set the font before adding the text:
VB.NET:
Public Sub AppendRegularText(ByVal RTC As RichTextBox, ByVal text As String)
    With RTC
        .Select(.TextLength, 0)
        .SelectionFont = New Font(.SelectionFont, FontStyle.Regular)
        .AppendText(text)
    End With
End Sub
Notice also I change the method to Sub. Function is for methods that return a value.

Otherwise, the problem of font style not 'sticking' is because in your code you assigned a completely new plain text to .Text property, causing all previous formatting to be removed.
 
Back
Top