Can't access form1 from form2

jdy0803

Well-known member
Joined
Sep 9, 2012
Messages
73
Location
Santa Clarita
Programming Experience
10+
I made form1, form2, Module1.

Module1 has Sub Main()
form1 has a label and a button. If click the button, call form2.
form1 call form2.
form2 has a button. If click the button, change label of the form1.

I tested in 2 ways.
1. In case of Startup Object is Sub Main() of Module1
Sub Main() => form1 => form2
2. In case of Startup Object is form1
form1 => form2

In case of 2, there's no problem.
But, in case of case 1(if I change Startup object from Project Properties window), form2 can't change form1's label(this means form2 can't change anything from form1)
Can somebody solve this problem?

Here is codes.
-------------------------
<Module1>
Module Module1
Sub Main()
Application.Run(New Form1)
End Sub
End Module
<form1>
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form2.Show()
End Sub
End Class
<form2>
Public Class Form2
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form1.Label1.Text = "AAAAA"
End Sub
End Class
-------------------------
 
Why exactly are you using your own Main method in the first place? If you weren't doing that then it would work. The reason that it's not working as you expect is that you are trying to access the default instance of Form1 but its not the default instance that you're showing in the first place. If you allowed the application framework to create the startup form for you, which is the default, then it would display the default instance, so when you later access the default instance you'd be accessing the same form object that you displayed. To learn more about default instances, follow the Blog link in my signature and check out my post on the subject.
 
Back
Top