Error using OpenFileDialog in VB.NET

0

I was trying to use OpenFileDialog in my button so that when I press it I get the dialogue, I do it in the following way:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim OpenFileDialog1 As OpenFileDialog
        With OpenFileDialog1
            .FileName = ""
            .Filter = ""
            .Title = ""
            .ShowDialog()
            TextBox1.Text = .FileName
            infectedfile = TextBox1.Text
        End With
    End Sub

But it returns the error:

Handles clause requires a WithEvents variable defined in the containing type or one of its base types. (BC30506) - C:\Users\Androide\Documents\SharpDevelop Projects\Form1\Form1\MainForm.vb:19,99

How can I avoid this error?

    
asked by Sergio Ramos 10.06.2017 в 21:32
source

2 answers

1

It seems that you create the openfiledialog dynamically, for this you must indicate that it is a new object, likewise I recommend that you start using the file only when it is selected, for this you could use the dialogresult of your openfiledialog.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim OpenFileDialog1 As New OpenFileDialog
    With OpenFileDialog1
        .Title = ""
        .Filter = ""
    End With
    If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
        TextBox1.Text = OpenFileDialog1.FileName
        infectedfile = TextBox1.Text
    End If

End Sub

Greetings!

    
answered by 28.06.2017 в 16:46
0

The error seems to indicate that the Button1 button is not created correctly.

If you have not created the button you can create it from the form designer by selecting the button in the toolbar and drawing it with the mouse on the form.

If you created it in the MainForm.designer.vb file, which is the file where the code created by the form designer is located, a statement similar to:

should appear
Private Sub InitializeComponent()
    Me.Button1 = New System.Windows.Forms.Button()
    Me.SuspendLayout()
    '
    'Button1
    '
    Me.Button1.Location = New System.Drawing.Point(62, 45)
    Me.Button1.Name = "Button1"
    
answered by 10.06.2017 в 21:48