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.EventArgs) Handles MyBase.Load
If Not IsNothing(f2) Then
If Not f2.IsDisposed Then
f2.WindowState