Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Upgrading  »  Multiple Forms in VB.NET. Part 3 - Using Events in Multiple Forms
 »  Home  »  Windows Development  »  Win Forms  »  Multiple Forms in VB.NET. Part 3 - Using Events in Multiple Forms
Multiple Forms in VB.NET. Part 3 - Using Events in Multiple Forms
by Ged Mead | Published  09/03/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 3 - Using Events in Multiple Forms

Article source code: multipleforms3.zip

As with the previous articles in this series, this one is also aimed at .NET Newbies and Upgraders. It tries to explain concepts as simply as possible, with the greatest use of plain English and minimum use of technical terms. The aim is to get the core ideas across as quickly as possible, so you can achieve the results you desire now; the technical details can follow in time. I know that many will not agree with this approach, but as a relative .NET Newbie myself, I know just how frustrating it can be trying to plough through a mass of technical detail in the early days when all you really want to do is, well, get started!

In this article, we are going to look at another topic on ways of dealing with multiple forms. As promised at the end of Part 2, we are first going to take a look at a way of passing data between multiple forms, but this time the user doesn't need to click a button to fire up the event.

Using Events

In our example project, we will have two forms. As the user enters data into a textbox in one form, this data will be copied to a label in the second form. Once again, although we're using a simple textbox for this example of the technique, the core idea can be extended for use in many much more sophisticated ways.

So, create two Windows Forms and name them EventsForm1 and EventsForm2. We'll be using EventsForm1 as the 'main' form, which is the one that has the label to receive the input data, and EventsForm2 as the form with the input textbox.

Here's the code we need to create an instance of EventsForm2. First, in EventsForm1, we declare a Form variable.

' This must be declared outside of any code blocks
    Dim WithEvents f2 As New EventsForm2()

Note that this has been declared WithEvents. This is important and if you leave it out, the main form will not be aware of what we are about to do in the second form.

And I thought that as we are being more dynamic in this Part, we would also instantiate and show the second form without user intervention. Or, in other words, we'll put it in the first form's load event and both forms will appear to the user at the same time.

Private Sub EventsForm1_Load(ByVal sender As Object_
    ByVal e As System.EventArgsHandles MyBase.Load

    If Not IsNothing(f2Then
        If Not f2.IsDisposed Then
            f2.WindowState = FormWindowState.Normal
            f2.BringToFront()
            f2.Show()
        Else
            f2 = New EventsForm2()
            f2.Show()
        End If
    Else
        f2 = New EventsForm2()
        f2.Show()
    End If

    '  Make sure it can be seen OK
    f2.Left = Me.Left + Me.Width + 2
    f2.Top = Me.Top

End Sub

Apart from the couple of lines at the end of that block, which just ensure that the two forms can be seen side by side, the instantiation code is the "test before instantiating" code which we covered in Part 1. (The code in Part 1 is quite well commented if you want to see the details.)

Add Some Controls

If you were to run the project at this point, you will be rewarded with two control-free forms side by side on your screen. Time to add some GUI items then.

In EventsForm1, add a Label. The size isn't critical, but you should allow for several lines of text to be visible. We'll name this label lblData.

In EventsForm2, add a Textbox. Delete the default Text property (usually this will be 'TextBox1') so that the user will see an empty textbox. Also set its MultiLine property to True. Finally, rename it as TB1.

The Events Code

Just to quickly recap what we are trying to do here: When the user types something into the textbox TB1 in EventsForm2, we want the text also to be displayed in the label in EventsForm1.

Let's add in the code to achieve this. We first need to declare an Event. We'll call this event TextHasChanged.

Here's the declaration; note that it has to be placed outside any code blocks, subs, etc.

Public Class EventsForm2
    Inherits System.Windows.Forms.Form

    '  Declare this event
    Event TextHasChanged()

Now, we need something to fire up this event. The obvious candidate in this particular scenario is the built-in TextChanged event of the textbox, so let's put some code in there to raise the warning flag that we are creating here.

Select the textbox TB1 in the code window and put this code in its TextChanged event handler:

Private Sub TB1_TextChanged(ByVal sender As Object_
    ByVal e As System.EventArgsHandles TB1.TextChanged
    '  If the user enters something here, then show it in the
    '  first form
    RaiseEvent TextHasChanged()

End Sub

All this does is to flag up the fact that text has changed by raising the Event that we declared and called TextHasChanged.

What will happen each time the user enters any character into the textbox is that the TextHasChanged event is raised. (This includes any editing of the text with the Delete or BackSpace keys too).

However, there's no point in waving the flag around (raising the event) if there's no lifeguard (in this case EventsForm1) looking out for it. So, finally, we'll tell EventsForm1 what to do if the TextHasChanged event in EventsForm1 is raised. (Technically, this is known as receiving the event.)

Back in EventsForm1, if you go into the Code Window and click on the left hand combo, you will see that the Object we have named f2 is available in that drop down list of Objects. Select it and then click on the right hand list of Events. You will see that our newly created event TextHasChanged is now included in the list of events, along with all the usual Windows Forms events that you'd expect to see there.

So let's select that item from the list and we will be able to put some code in the TextHasChanged Event's Event Handler:

Private Sub f2_TextHasChanged() Handles f2.TextHasChanged
    Me.lblData.Text = f2.TB1.Text
End Sub

You'll understand that all this code really does is to copy the text from the textbox on the other form into the label on this form. But because we have linked this event to react to every change of character in that textbox, the user will see the text displayed in the label dynamically as it is being typed. If you run the project now and type in some text, you will see this in action.

Summary

There are of course always alternative ways of achieving the same result, but I took the example of a textbox used here as a simple demonstration of the sort of thing you can do with passing events between multiple forms. It's sometimes difficult to find examples that aren't too artificial, but hopefully this basic example will be enough to show you how to use the technique in a variety of more advanced and exciting ways, according to your needs in projects and applications. I hope you find it a useful introduction to the very basics of Events, as well as simply showing you another way of passing data between multiple forms.

My thanks to fellow vbCity Member George Poth for proofreading this article and for creating the attached Visual Studio Solution from the narrative.

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:4.52439024390246 out of 5
 164 people have rated this page
Article Score87582
Sponsored Links