Aaron Warnke Aaron Warnke - 1 month ago 9
Vb.net Question

How to op-en file and view in a rich text box using vb.net?

Hi I am trying to open and view a files text in a rich text box. Here is what I have please let me know what I am doing wrong?

Private Sub loadButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles loadButton.Click

' Displays an OpenFileDialog so the user can select a Cursor.
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "Cursor Files|*.txt"
openFileDialog1.Title = "Select a Cursor File"

If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
' Assign the cursor in the Stream to the Form's Cursor property.
Me.mainRTBox = New Text(openFileDialog1.OpenFile())
End If

End Sub

Answer

The problem you were having was that you weren't reading the file at all, and you weren't assigning the content of the file to the RichTextBox correctly.

Specifically, this code you have:

Me.mainRTBox = New Text(openFileDialog1.OpenFile())

.. should be:

Me.mainRTBox.Text = FileIO.FileSystem.ReadAllText(openFileDialog1.FileName)

This code will work:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' Displays an OpenFileDialog so the user can select a Cursor.
        Dim openFileDialog1 As New OpenFileDialog()
        openFileDialog1.Filter = "Cursor Files|*.cur"
        openFileDialog1.Title = "Select a Cursor File"

        If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            ' Assign the cursor in the Stream to the Form's Cursor property.

            Dim extension = openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("."))

            If extension Is "cur" Then
                Me.mainRTBox.Text = FileIO.FileSystem.ReadAllText(openFileDialog1.FileName)
            End If

        End If
    End Sub
End Class

Edit: I updated the code so that it checks if the user did actually open a Cur (cursor) file.

Comments