AHM3D AHM3D - 4 months ago 36
Vb.net Question

openfiledialog give error on cancel button , Visual Basic & i am suing this code

ofd.ShowDialog()
If ofd.FileName = Nothing Then

ElseIf ofd.FileName = DialogResult.OK Then
Dim fl As String
fl = ofd.FileName
Dim sr As New StreamReader(fl)
TextBox1.Text = sr.ReadToEnd()
sr.Close()
End If

Answer

You can check what button the user has pressed by checking the return value of ShowDialog(). Checking for OK (returned when you actually select a file) should fix your problem getting errors when you press Cancel.

If ofd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
    Dim fl As String
    fl = ofd.FileName

    Dim sr As New StreamReader(fl)
    TextBox1.Text = sr.ReadToEnd()
    sr.Close()
End If
Comments