如何从原始窗体1调用新窗体1中的子/函数



更新:
Frm1A as new Form from Form1

我只想在Form1中使用MainCal_Click来订购所有新表单以使用每个表单的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

这是怎么回事?

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

我碰巧在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

最新更新