Notes:
- No need to check the extension after you show the form, but you should instead set the appropriate filter in order to limit the selection of
.txt
files only"txt files (*.txt)|*.txt"
- You can use the
OpenFileDialiog.CheckFileExists
andOpenFileDialiog.CheckPathExists
properties to prevent user to enter an invalid file name/path (display an error message) - Not sure you need to check a second time if the file exists if you use
CheckFileExists
/CheckPathExists
- You should always dispose a form that you show using
ShowDialog()
method. - You should dispose the
StreamReader
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Using ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt"
ofd1.FilterIndex = 2
ofd1.CheckPathExists = True
ofd1.CheckPathExists = True
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
filename = ofd1.FileName
Using objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End Using
End If
End Using