如何从原始Form1调用New Form1中的Sub / Function?

时间:2018-11-15 04:09:30

标签: vb.net

更新:
Frm1A as new Form from Form1

我只想在MainCal_Click中使用Form1来订购所有新表单以使用每种表单的Sub Cal

Class Form1

  Dim Data as integer

  Sub Cal(byval x as integer)
     Data = Data + x
  End Sub

  Private Sub LoadOthForm_Click() 'Every time to create new Form when Click 
    Dim Frm1A as New Form1
    Frm1A.text = "Form1"..."Form2"... 'May 100+ Form  
    Frm1A.Show       
  End Sub

  Private Sub MainCal_Click() 'When click, it will order all new open form run Sub Cal()
    Data = 100
    For each frm as Form in Application.OpenForm
      if frm.Text = "From1" then
          frm.Cal(5) .......**** 'What code that new From can use Sub Cal ()? ****
      End if
      if frm.Text = "From2" then
          frm.Cal(15)
      End if
    Next
  End Sub

End Class

2 个答案:

答案 0 :(得分:0)

我碰巧在Form3上,但其工作原理与Form1相同。您需要引用所创建的新表单,以便在其上调用方法。我在类级别制作了表单变量,因此可以在LoadOthForm_Click和MainCal_Click方法中使用它们。您已经为新表单实例指定了Name属性,因此无法通过这种方式找到它们。您需要为每个表单设置Data属性,因为每个表单都有自己的Data属性。它是一个类级别字段,而不是全局字段。它添加了一个标签来显示Cal方法的结果,以证明表单正在运行该方法。

Public Class Form3
    Dim Data As Integer
    Dim Frm1A As Form3
    Dim Frm1B As Form3
    Dim Frm1C As Form3
    Sub Cal(ByVal x As Integer)
        Data = Data + x
        Label1.Text = Data.ToString
    End Sub

    Private Sub MainCal_Click(sender As Object, e As EventArgs) Handles MainCal.Click
        Frm1A.Data = 100
        Frm1B.Data = 100
        Frm1A.Cal(5)
        Frm1B.Cal(15)
    End Sub

    Private Sub LoadOthForm_Click(sender As Object, e As EventArgs) Handles LoadOthForm.Click
        Frm1A = New Form3()
        Frm1B = New Form3()
        Frm1C = New Form3()
        Frm1A.Show()
        Frm1B.Show()
        Frm1C.Show()
    End Sub
End Class

答案 1 :(得分:0)

这怎么样?

Class Form1

    Private Data As Integer

    Sub Cal(ByVal x As Integer)
        Data = Data + x
        MsgBox(String.Format("{0}:{1}", Me.Text, Data.ToString))
    End Sub

    Private Sub LoadOthForm_Click(sender As Object, e As EventArgs) Handles LoadOthForm.Click
        For i = 1 To 10
            Dim f As New Form1
            f.Text = "FormA" + i.ToString
            f.Show()
        Next
    End Sub

    Private Sub MainCal_Click(sender As Object, e As EventArgs) Handles MainCal.Click
        Data = 100
        For Each frm As Form In Application.OpenForms
            If frm.Text = "FormA1" Then
                CType(frm, Form1).Cal(5)
            End If
            If frm.Text = "FormA2" Then
                CType(frm, Form1).Cal(15)
            End If
        Next
    End Sub

End Class