|
-
Nov 19th, 2004, 06:18 AM
#1
Thread Starter
PowerPoster
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"
__________________
Last edited by taxes; Dec 19th, 2004 at 10:25 AM.
Reason: addition to title
Taxes
The more I learn about VB.NET the more I like dBaseIII Plus
The foregoing, whilst believed to be correct, is given without guarantee as to it's accuracy and entirely without recourse. You are required to decide for yourself whether or not it is suitable for your purposes and no liability for loss of any nature can be entertained.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|