Click a button on another open form in vb.net

Hi all.

I have a form Form1 that I use to display some records, this form has 2 buttons: button1 and button2

Button1 is used to open Form2. Form2 has a button: btnSave

When I click the btnSave button on Form2 it does some things and I want it to click button2 from Form1.

Unfortunately, the code I'm using doesn't click the button2 on Form1.

Here is the code for button1 on Form1:

Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
         Dim frm As New Form2
 frm.Show()
    End Sub

Open in new window


Here is the code for button2 on Form2:
Public Sub button2_Click(sender As Object, e As EventArgs) Handles button2.Click
DataGridView1.DataSource = GetDataTable_WB()
End Sub

Open in new window


Here's the code for btnSave on Form2:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'
'
'
cmd.ExecuteNonQuery()
MessageBox.Show("Save Done")

con.Close()

        Me.Close()

Form1.button2.PerformClick()
End Sub

Open in new window


I also tried:
Form1.button2_Click(Form1.button2_Click, EventArgs.Empty)

But nothing happens. It doesn't run the code for button2 on Form1

Thank you in advance!
printmediaAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
Two ways you can accomplish your goal, subscribe to an event listener on Form2 or pass an instance of Form1 into Form2 and call the method directly.

Proof of concept -

Form1.vb -
Public Class Form1
    Private Sub OnClick(sender As Object, e As EventArgs) Handles Button3.Click, Button2.Click, Button1.Click
        If TypeOf sender Is Button Then
            Dim btn = DirectCast(sender, Button)
            If btn.Equals(Button1) Then
                Dim [form2] = New Form2()
                AddHandler form2.ButtonPressed, AddressOf OnButtonPressed
                form2.Show()
            ElseIf btn.Equals(Button2) Then
                Dim [form3] = New Form3(Me)
                form3.Show()
            ElseIf btn.Equals(Button3) Then
                MessageBox.Show("Target button was pressed in Form1")
            End If
        End If
    End Sub

    Private Sub OnButtonPressed(ByVal sender As Object, ByVal e As EventArgs)
        OnClick(Button3, e)
    End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Button3 = New System.Windows.Forms.Button()
        Me.Button2 = New System.Windows.Forms.Button()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'Button3
        '
        Me.Button3.Location = New System.Drawing.Point(12, 70)
        Me.Button3.Name = "Button3"
        Me.Button3.Size = New System.Drawing.Size(260, 23)
        Me.Button3.TabIndex = 5
        Me.Button3.Text = "Taget Button"
        Me.Button3.UseVisualStyleBackColor = True
        '
        'Button2
        '
        Me.Button2.Location = New System.Drawing.Point(12, 41)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(260, 23)
        Me.Button2.TabIndex = 4
        Me.Button2.Text = "Open Form3"
        Me.Button2.UseVisualStyleBackColor = True
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(12, 12)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(260, 23)
        Me.Button1.TabIndex = 3
        Me.Button1.Text = "Open Form2"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(284, 101)
        Me.Controls.Add(Me.Button3)
        Me.Controls.Add(Me.Button2)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

    Friend WithEvents Button3 As Button
    Friend WithEvents Button2 As Button
    Friend WithEvents Button1 As Button
End Class

Open in new window

Form2.vb -
Public Class Form2
    Private ReadOnly _buttonPressed As New List(Of EventHandler)
    Public Custom Event ButtonPressed As EventHandler
        AddHandler(value As EventHandler)
            _buttonPressed.Add(value)
        End AddHandler

        RemoveHandler(value As EventHandler)
            _buttonPressed.Remove(value)
        End RemoveHandler

        RaiseEvent(sender As Object, e As EventArgs)
            For Each handler As EventHandler In _buttonPressed
                Try
                    handler.Invoke(sender, e)
                Catch ex As Exception

                End Try
            Next
        End RaiseEvent
    End Event


    Private Sub OnClick(sender As Object, e As EventArgs) Handles Button1.Click
        RaiseEvent ButtonPressed(sender, e)
        Close()
    End Sub
End Class

Open in new window

Form2.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form2
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(13, 13)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(259, 23)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Press Target"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'Form2
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(284, 45)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form2"
        Me.Text = "Form2"
        Me.ResumeLayout(False)

    End Sub

    Friend WithEvents Button1 As Button
End Class

Open in new window

Form3.vb -
Public Class Form3
    Public Sub New(instance As Form1)
        InitializeComponent()
        Form1 = instance
    End Sub

    Private Sub OnClick(sender As Object, e As EventArgs) Handles Button1.Click
        Form1.Button3.PerformClick()
        Close()
    End Sub
End Class

Open in new window

Form3.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form3
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(13, 13)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(259, 23)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Press Target"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'Form3
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(284, 45)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form3"
        Me.Text = "Form3"
        Me.ResumeLayout(False)

    End Sub

    Friend WithEvents Button1 As Button
    Friend WithEvents [Form1] As Form1
End Class

Open in new window

Produces the following output -
Initial load -Capture.PNGOpen Form2 Pressed -Capture.PNGPressing Target Button on Form2 -Capture.PNGOpen Form3 Pressed -Capture.PNGPressing Target Button on Form3 -Capture.PNG
-saige-
0
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
Another option is to display Form2 with ShowDialog(), instead of Show(), which will cause execution in Form1 to STOP until Form2 is dismissed:
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
    Dim frm As New Form2
    frm.ShowDialog() ' <-- code stops here in Form1 until "frm" is dismissed

    button1.PerformClick() ' click button1 now
End Sub

Open in new window


Once Form2 is dismissed, button1 will be clicked.  Over in Form2, you simply close the form:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
    cmd.ExecuteNonQuery()
    MessageBox.Show("Save Done")
    con.Close()

    Me.Close() ' <-- just close Form2, and execution will continue in Form1, AFTER the ShowDialog() line
End Sub

Open in new window


This obviously will only work if it is acceptable to not be able to access Form1 while Form2 is open.
0
printmediaAuthor Commented:
Mike I tried your suggestion and it still doesn't work. And yes it's ok that Form1 is not accessible while Form2 is open.
0
printmediaAuthor Commented:
I found a way by adding the following code to Form1 in the "Activated" event for the form:

button2.PerformClick()

Open in new window


Thank you for your help.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
printmediaAuthor Commented:
I solved it on my own.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.