Form References: Communication Between Forms

Team Fly 

Page 45

Form References: Communication Between Forms

Before VB.NET, you could reference a form's properties in code inside that form by merely specifying a property (leaving off the name of the form):

 BackColor = vbBlue 

Or to reference a form from outside that form: If you want to show or adjust properties of controls in one form (by writing programming in a second form), you merely use the outside form's name in your code. For instance, in a CommandButton_Click event in Form1, you can Show Form2, and change the ForeColor of a TextBox on Form2, like this:

 Sub Command1_Click () Form2.Show Form2.Text1.ForeColor = vbBlue End Sub 

Now in VB.NET, when you reference a form's properties from code inside the form, you must use Me:

 Me.BackColor = Color.Blue 

And to manipulate a form's contents from outside the form: Say that you want to be able to contact Form2 from within Form1. You want to avoid creating clone after clone of Form2. If you use the New statement willy-nilly all over the place (Dim FS As New Form2), you'll be propagating multiple copies of Form2, which is not what you want. You don't want lots of windows floating around in the user's Taskbar, all of them clones of the original Form2. Remember that every time you use As New, you instantiate a new object.

Instead, you want to be able to communicate with the single, original Form2 object from Form1. But how can you do that? How can you create an object variable in Form1 that references Form2?

One way to do this is to create a public variable in Form1, like this:

 Public f2 As New Form2 Private Sub Form1_Load(ByVal sender As System.Object, _  ByVal e As System.EventArgs) Handles MyBase.Load         f2.Show()         f2.BackColor = Color.Blue End Sub 

Form1 is instantiated first when a VB.NET project executes (by default, it is the ''startup object") in any Windows-style VB.NET project. So, by creating a Public variable that instantiates Form2 (the New keyword does that), you can then reference this variable (F2 here) any time you need to manipulate Form2's properties or methods from within Form1. It's now possible for Form1 to be a client of Form2, in other words.

The problem of communicating from Form2 to Form1, however, is somewhat more complex. You cannot use the New keyword in Form2 or any other form because that would create a second Form1. Form1 already exists because it is the default startup object.

Team Fly 


Visual Basic  .NET Power Tools
Visual Basic .NET Power Tools
ISBN: 0782142427
EAN: 2147483647
Year: 2003
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net