Somanna
Somanna

Reputation: 336

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.

Upvotes: 0

Views: 600

Answers (2)

user13563549
user13563549

Reputation:

Just as Idle_Mind says, .ShowDialog() will stop the following code from working, so you have two ways around it.

  • First invoke the event, and then show it as a dialog

    Dim frm as New form2
    frm.button2.PerformClick()
    frm.ShowDialog()
    
  • Keep it as it is, but instead of showing it as a dialog, just show it.

    Dim frm as New form2
    frm.Show()
    frm.Visible = True
    frm.button2.PerformClick()
    

Upvotes: 0

Idle_Mind
Idle_Mind

Reputation: 39122

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

Upvotes: 1

Related Questions