Forms (Classes), Control, Accessing one Form (Class) From Another (Beginners Only)
Hi,
In one version or another this seems to be the most frequently asked question by beginners. I do not pretend that this code is "State of Art" but I have been asked to put it here for ease of reference so here goes.
To access any object (variable or control etc) or method in FormA from any other form, whether a child form or not FormA cannot have been instantiated as Private. You must use the Public or Friend keyword ( or their close relatives see below). The easiest way to do this is to use a Module Sub Main as your project startup object and in that module put:
VB Code:
Public frmA AS New fclsA (assuming your designed form is named
fclsA)
Public Sub Main()
Application.Run(frmA)
End Sub
You then have to ensure that all the objects/methods which you wish to access in fclsA are declared as Shared or Public. With a control you do this in the design window by setting the Modifiers property of the object to Shared etc. With a variable, you declare it in the general section of the code view as Shared or Public or Friend e.g. Public sString As String. With a method or event you use Shared or Public or Friend as the first word. e.g.
Public Sub TestCode ()
....
....
End Sub
or
Friend Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub
So, assuming that when a button is clicked in FormB you want Label1 in fclsA to show that button's text:
VB Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Form1.Label1.Text = Me.Button1.Text
End Sub
(Notice that this button does not need to be declared Public as it is not the target of the code.)
There are other ways to create the instance of the form and start your project, but they all observe the above requirements.
NOTE: The use of "Friend" includes "Protected Friend"
__________________