Search code examples
vb.netbuttoninstanceshowdialog

Cannot raise button click event of another form


I've two forms form1 and form2. form1 has button1 and form2 has button2. What I want to achive is when I click on button1 form2 should be shown and button2 must get clicked. I've tried the below mentioned codes inside button1 click event.

form2.ShowDialog
form2.button2.PerformClick

Or

form2.ShowDialog
form2.button2_Click(Nothing, Nothing)

Or

Dim frm as New form2
frm.ShowDialog
frm.button2.PerformClick

Or

Dim frm as New form2
frm.ShowDialog
frm.button2_Click(Nothing, Nothing)

But none of the above mentioned methods are working. Only form2 is shown but button2 is not being clicked.

I've tried again by making 'button2_Click' event public but still it's not working.


Solution

  • The problem with your current approach is that code STOPS in the current form when ShowDialog() is run.

    One solution would be to create an instance of Form2 and wire up the Shown() event, which gets run AFTER the form is displayed.

    From there, you can click the button using the instance of the form you created:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim f2 As New Form2
        AddHandler f2.Shown, Sub()
                                 f2.Button2.PerformClick()
                             End Sub
        f2.ShowDialog()
    End Sub