Search code examples
vb.nettoolstripmenu

MDI parent form toolstrip button control MDI child


I want to make the toolstrip button on MDI parent to be able perform MySQL command for MDI child

I have try to create button in MDI child with an MySQL command and try to access from MDI parent toolstrip event handler using mdiform.button.PerformClick but not successful


Solution

  • From the ToolStrip Button handler, you can check the type of ActiveMdiChild to make sure it is the correct type of MdiChild form, then cast it and tell the button to click itself.

    For instance, my MdiParent is Form1, and the MdiChild is Form2:

    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim f2 As New Form2
            f2.MdiParent = Me
            f2.Show()
    
            Dim f3 As New Form3
            f3.MdiParent = Me
            f3.Show()
        End Sub
    
        Private Sub ToolStripButton1_Click(sender As Object, e As EventArgs) Handles ToolStripButton1.Click
            Dim frm As Form = Me.ActiveMdiChild
            If Not IsNothing(frm) AndAlso TypeOf frm Is Form2 Then
                Dim childF2 As Form2 = DirectCast(frm, Form2)
                childF2.Button1.PerformClick()
            End If
        End Sub
    
    End Class
    
    Public Class Form2
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            MessageBox.Show("Hello World!")
        End Sub
    
    End Class
    

    Here it is running. Note how the ToolStrip button only works if the Active MdiChild is of type Form2, and not Form3:

    enter image description here