Error Handling: load text file into TextBox

J

jzheng22

Hi all,

I am new to VB .NET. I am currently wring a simple GUI, a TextBox
(multilined),
a button and an OpenFileDialog. When user click the button, the
OpenFileDialog
fired and after user select a file, the content of the text file would
be loaded
(appended) into the TextBox.
Note: I am not using RichTextBox.Loadfile() method.

My code is working, however, when i tested it by loading large .exe
file into the
textbox, the program freezes. I wondered if anyone could help me with
these:
1) check if the selected file is a text file
2) if user choose a very large file, no matter what format it is, the
code should
report an exception and keep running.

Many thanks.

P.S. My current error handlers using "Try" are not working, code
attached below:

Try
If OpenFileDialog1.ShowDialog() =
System.Windows.Forms.DialogResult.OK _
And (OpenFileDialog1.FileName.Length) > 0 Then

Dim objReader As New StreamReader(OpenFileDialog1.FileName)
Dim sLine As String = ""
Do
sLine = objReader.ReadLine()
If Not sLine Is Nothing Then
TextBox1.Text = TextBox1.Text & "; " &
sLine
End If
End If
Loop Until sLine Is Nothing
objReader.Close()
End If
Catch ex As Exception
MessageBox.Show("Error when open files." & vbCrLf &
ex.Message)
TextBox1.Clear()
TextBox1.Focus()
Exit Sub
End Try
 
C

Cor Ligthert [MVP]

JsHeng,

There is a size bug in the Version Net 1.1 in the textbox

Can it be that you are using a version from before 2005?

Cor
 
P

Peter Proost

Hi you can use the openfiledialog filter property to allow only textfiles,
see code below

Dim myReader As StreamReader
OpenFileDialog1.Filter = "Text files|*.txt"
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
try
myReader = New StreamReader(OpenFileDialog1.FileName)
TextBox1.Text = myReader.ReadToEnd
myReader.Close()
catch ex As Exception
messageBox.show(ex.ToString)
end try
End If

Hope this helps,

Greetz Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top