Update:
Frm1A as new Form from Form1
.
I want to use only MainCal_Click
in Form1
to order all new Forms to use Sub Cal
of each Form.
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
I happen to be on Form3 but it works the same as Form1. You need to have a reference to the new forms you create in order to call methods on them. I made the form variables at the class level so you could use them in both the LoadOthForm_Click and the MainCal_Click methods. You neve gave your new form instances a Name property so you cannot find them that way. You need to set the Data property for each form because each form has its own Data property. It is a class level field not a global. It added a label to show the result of the Cal method to demonstrate that the forms are running the method.
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
How is this?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.