Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Upgrading  »  Multiple Forms in VB.NET. Part 2 - Accessing Controls on Other Forms
 »  Home  »  Windows Development  »  Win Forms  »  Multiple Forms in VB.NET. Part 2 - Accessing Controls on Other Forms
Multiple Forms in VB.NET. Part 2 - Accessing Controls on Other Forms
by Ged Mead | Published  07/23/2003 | Upgrading Win Forms | Rating:
Ged Mead

Ged Mead (XTab) is a Microsoft Visual Basic MVP who has been working on computer software and design for more than 25 years. His journey has taken him through many different facets of IT. These include training as a Systems Analyst, working in a mainframe software development environment, creating financial management systems and a short time spent on military laptop systems in the days when it took two strong men to carry a 'mobile' system.

Based in an idyllic lochside location in the West of Scotland, he is currently involved in an ever-widening range of VB.NET, WPF and Silverlight development projects. Now working in a consultancy environment, his passion however still remains helping students and professional developers to take advantage of the ever increasing range of sophisticated tools available to them.

Ged is a regular contributor to forums on vbCity and authors articles for DevCity. He is a moderator on VBCity and the MSDN Tech Forums and spends a lot of time answering technical questions there and in several other VB forum sites. Senior Editor for DevCity.NET, vbCity Developer Community Leader and Admin, and DevCity.NET Newsletter Editor. He has written and continues to tutor a number of free online courses for VB.NET developers.


View all articles by Ged Mead...
Multiple Forms in VB.NET. Part 2 - Accessing Controls on Other Forms

Article source code:

One of the key mindset changes you have to make as part of your move from VB6 to VB.NET is the status of Windows Forms. In the early days of VB, Forms were King. Now, VB.NET changes the picture and - although they are still important in many applications - Windows Forms should in many cases be viewed as simply another class and be dealt with accordingly.

If you keep this in mind, many of the early learning curve problems of the move to VB.NET are easier to overcome. We dealt with how to load, show, hide and close multiple forms in Multiple Forms in VB.NET: Part 1. You saw there that the answer to most VB6 to VB.NET misunderstandings in this area was to deal with each form as an object of the Form Class.

In this article, we will take an initial look at some ways of accessing other form's controls and passing data between forms; and our approach to this is going to be pretty much the same as in the earlier article.

This is written for fellow .NET Newbies and so it avoids some of the more advanced topics and skills. It is intended only to give you a hand to get started with the basics of accessing one form and its data from another the .NET way, using an object oriented approach. As always with .NET, there's lots of scope for further study!

Accessing Another Form's Controls

When you are dealing with Windows Forms it's quite likely that sooner or later you are going to want to pass the data held in a control on one form over to another form. For example, the text a user has entered in a text box, a selection from a combobox, a checkbox's Checked property, etc. You may also want to insert data into a control on another form.

Remembering that everything in VB.NET is an object, and that we want to leave our VB.Old ways behind us and think OOP, the trick here is to deal with the control we want to access as an object in its own right.

So let's take one of the examples from the first paragraph above and see how we go about achieving this. I'm going to take the first one - passing the text from a textbox in Form2 back to Form1 - as this is relatively common and straightforward.

Example 1: Reading Another Form's TextBox

In this example we'll assume that it's acceptable for the second form to be opened modally (that is, the user can't do anything with the first form until the second form has been closed.) In many cases, this will be fine.

Here are the steps:

  1. Create Two Windows Forms (Form1 and Form2*)
  2. Form1: Add a Button (named 'ShowButton') and a Label (named 'UserLabel').
  3. Form2: Add a TextBox (named 'UsersName') and a Button (named 'CloseButton').

(* It's not usually considered a good idea to use names that don't reveal any information - such as Form1, TextBox1, etc. However, I've kept to Form1 and Form2 in this example as it's useful to make it clear which form is doing the calling and which is being called.)

And now to start the coding. In Form1, we need an Object Variable to manipulate the second form.

Public Class Form1
    Inherits System.Windows.Forms.Form

    Dim F2 As New Form2()  ' Object variable

In the Click_Event handler for the ShowButton, enter this code:

    F2.ShowDialog(Me)  ' Show Form2

There is some more code needed for that button click event, but we'll come back to it in a moment.

In Form2, we create another Object Variable, but this time it will hold a TextBox control, not a Form.

Public Class Form2
    Inherits System.Windows.Forms.Form

    Public Shared NuNameTB As TextBox

Notice that the scope of this variable is 'Public Shared'. This is important as this scope declaration makes the variable visible to the other form (and in fact the rest of the application).

Still in Form2, we put the following code in the Click event of the button:

Private Sub CloseButton_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles CloseButton.Click
    ' Assign this form's TextBox to the Object Variable
    NuNameTB = UsersName
    ' Now close the form
End Sub

With that very simple code, we have made the properties of our TextBox in Form2 available to the user back in Form1. NuNameTB is now effectively a TextBox Object, whose Text property is the same as Form2's UsersName.Text property.

I said we'd have to come back to the code block for the ShowButton Click in Form1. If you have entered all the above code and have run it, you will be back with Form1 on view, but there's no evidence that what I have just said is true. So, here's the proof:-

At the bottom of the Click event for Form1's ShowButton, add this:

    Me.UserLabel.Text = "Current User : " & F2.NuNameTB.Text

Run this now and, once you've closed down Form2, you will see that whatever you typed into the TextBox on Form2 is available and displayed in the label on Form1.

Note that although this example uses the most obvious property of the TextBox (the Text property), you can in fact access any of that TextBox's properties if you need to. By the way, if you're wondering why we've done it this way with an object variable and not accessed the textbox directly, then the plain answer is 'Think OOP'.

Example 2: Using a Property Procedure

So that was a fairly uncomplicated example which will do the job for you in many circumstances. Let's rack up the OOP factor another notch and this time use a Property Procedure as our means of passing the data around. This fits in with one of the cornerstones of OOP - Abstraction.

In my non-technical way, I like to think of Abstraction as the provision of a general purpose front end that continues to function properly even if we tweak about with the code at the 'back end'. In the example that follows, for instance, we could remove the textbox from Form2 and use some other means of feeding data into its UserName Property. The code in Form1 would be oblivious to the change and still work perfectly well.

I am again going to use a textbox as the control we are focusing on, but don't let this give you the mistaken impression that you are limited to textboxes. They just happen to be easy to use as examples. Set up your project as follows:

  1. Create Two Windows Forms (Form1 and Form2)
  2. Form1: Add a Button (named 'ShowButton') and a Label (named 'UserLabel').
  3. Form2: Add a TextBox (named 'UsersNameTextBox').

As in the previous example, we need an Object Variable In Form1 to allow us to show the second form.

Public Class Form1
    Inherits System.Windows.Forms.Form

    Dim F2 As New Form2()  ' Object variable

And we can add this code to Form1's Load event in order to have both forms on view at the same time:

    F2.Show  ' Show Form2

So far, this example and the previous one are very similar. We start to diverge at this point. Let's create that Property on Form2 which will hold the contents of TextBox1 (or whatever else we later choose to store in the UserName property).

In Form2, we will create a ReadOnly Property called UserName. Why Read Only? Well, it's not strictly necessary, but for the purposes of this simple example it will ensure that data cannot be passed back from Form1 and used to populate the TextBox in Form2.

Here's the code to go into Form2:

Public ReadOnly Property UserName() As String
        Return UsersNameTextBox.Text
    End Get
End Property

As you can see, all this Property does is hold the value of the text that the user enters into the textbox on Form2.

Now, what we want to happen is that when the user clicks on the button in Form1, the label on Form1 will be updated with the contents of the textbox on Form2. (Actually, to be more accurate, the contents of the UserName Property from Form2, remembering what I said earlier about Abstraction).

So in Form1, in the Click_Event handler for the ShowButton, enter this code:

Private Sub ShowButton_Click(ByVal sender As System.Object_
    ByVal e As System.EventArgsHandles ShowButton.Click
    Me.UserLabel.Text = F2.UserName
End Sub

To see this example working, run the project and make sure that you have positioned the two forms so that you can see both on the screen at the same time. Enter a name into the textbox on Form2. Click on the button on Form1. The label on Form1 will be updated with whatever you have entered into that textbox.

Change the textbox entry, click the button again and the label will change accordingly.

OK, now no-one's pretending that this is anything like a real-world scenario; it's a very artificial project, designed only to demonstrate that you can pass the data from the control on one form to a control on another form. Structurally it has more holes than a piece of Gruyere cheese, but it serves its purpose. Hopefully, you can see more realistic ways in which you can employ this basic technique.

The attached Solution includes the two examples from this article.

In the next article, we will look at rather more dynamic ways of getting hold of this cross-forms data. By this I mean the kind of scenarios where Form1 can be automatically updated when data in Form2 changes - no more of this 'pressing a button to make something happen' nonsense. We'll be tying our Form Properties in with Events and Event Handlers for a much slicker, user friendly and professional looking application. But in the meantime the two examples in this article have at least got the basics under our belts.

Related devCity.NET articles:

How would you rate the quality of this article?
1 2 3 4 5
Poor Excellent
Tell us why you rated this way (optional):

Article Rating
The average rating is: No-one else has rated this article yet.

Article rating:1.5332244008715 out of 5
 1836 people have rated this page
Article Score159720
Sponsored Links