We help IT Professionals succeed at work.

VB.net Read contents of a RichTextBox line by line

Murray Brown
Murray Brown asked
on
Hi

I have a RichTextBox that users populate using buttons with code like that below
What VB.net code do I use to loop through multiple lines?

  Private Sub btnAddRange_Click(sender As System.Object, e As System.EventArgs) Handles btnAddRange.Click
        Try
            Me.RichTextBox1.Text = Me.RichTextBox1.Text & " " & Me.txtRange.Text
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub btnNewLine_Click(sender As System.Object, e As System.EventArgs) Handles btnNewLine.Click
        Try
            Me.RichTextBox1.Text = Me.RichTextBox1.Text & " " & vbCrLf
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
Comment
Watch Question

Retired
Distinguished Expert 2017
Commented:
Hi murbro;

The RichTextBox has a Lines property which is an array of String which can be indexed or enumerated through to get each individual line in the control.

Dim line4 As String = RichTextBox1.Lines(3)
John RugoSenior SQL DBA

Commented:
Can you not just load the file into the RichTextBox?
RichtextBox1.Load("file path/name")
John RugoSenior SQL DBA

Commented:
Sorry, made a mistake in the code....
RichtextBox1.LoadFile("file path/name")

Open in new window

Fernando SotoRetired
Distinguished Expert 2017

Commented:
@Thunder724

 The user of the application selects a button and then a value is added to the RichTextBox, all at run time, dynamically.
John RugoSenior SQL DBA
Commented:
You can put each line into an array and then reference the array..

DIM RTFLines() As String
RTFLines = SPLIT(RichTextBox1.Text, VbCrLF)

'Loop through each row now in the array adding to a Listbox (example)
FOR X AS INT16 = 0 TO UBOUND(RTFLines) -1
    ListBox1.Add(RTFLines(x).ToString)
NEXT

Open in new window

Murray BrownASP.net/VBA/VSTO Developer

Author

Commented:
Thanks a lot for the help