Charlie
Charlie

Reputation: 13

vb.net 2010 append text always at top of a richtextbox

I have create a simple function to append text to a Richtextbox. I want that this text is append always on top scrolling the old text to the bottom.

Private Sub BoxMessaggio(ByVal testo As String, ByVal errore As Integer)
    Me.ActiveControl = RichTextBox1
    RichTextBox1.Focus()
    If errore Then
        RichTextBox1.SelectionColor = Color.Red
    Else
        RichTextBox1.SelectionColor = Color.Black
    End If
    RichTextBox1.AppendText(testo + vbNewLine)
    RichTextBox1.SelectionStart = RichTextBox1.Text.Length
    'RichTextBox1.Select(RichTextBox1.TextLength, 0)
    RichTextBox1.ScrollToCaret()
End Sub

I call the function in this way:

BoxMessaggio(Now + ": " + ex.Message, 1)

I tried a lot of different solutions found here on StackOverflow or in some forums but no one works for me, text is always add at the bottom....

Upvotes: 1

Views: 2688

Answers (1)

Keith
Keith

Reputation: 1321

Treat the RichTextBox1.Text as a String (because it is), call Insert, and place the new text at the front of the strong.

RichTextBox1.Text = RichTextBox1.Text.Insert(0, testo + vbNewLine)

As for the scrolling. Don't call Focus or ScrollToCaret and it will stay at the top viewing the most recently added text.

Upvotes: 2

Related Questions