Code - Financial Independence

Visual Basic/C# Tutorial 22 – Dealing with multiple forms

Why do that?

Sometimes it’s useful to have more than just one form in a project. For example, if you need more room or you want the user to make a selection or complete an action that is separated from the current form. Dealing with multiple Windows forms might seem a bit tricky but it isn’t.

How to create a new form?

Creating a new form in your project is as easy as creating a class!

1. Right-click on your project.
2. Select Add New Item.

3. Select in the list: Windows Form.
4. Give it a relevant name.

Starting the Form

Once you have your new form, it will be treated just like a class. You will be able to call it in your parent form.

We will add a new button in our parent form that we will use to launch the child form. Select a button from the toolbox in your parent form’s design editor and drag it on the form itself. Then double-click on the button as we’ve seen in the past tutorials to create its standard event which is Click.

I strongly suggest that you rename the button by changing its (Name) property and change its Text property as well. That should give you something like the following image.

To launch the child form, you create an instance of this form in the button click method in your parent form. Then call the Show() method of the child form you have just created. The following example should clarify this statement:

There is more to it!

That’s it! But it’s not over yet, you can add parameters to your child form’s constructor to be able to pass information to this form before it’s launched. For example, if you want to tell the child form information about the current edited client (let’s say the form is used to edit clients).

Let’s simplify this example and pass the form title instead. The code below shows my second form (please note that the namespace might defer depending on your project name, same this for the form name).

Lastly, you can click on the button and it will launch the second form with its new title just like the image below.

There is more!

Launching a Windows form from another Windows form is pretty easy and can be really useful to separate information and make the user experience easier to understand. There is in fact more to the subject like how to create closing events for the child form but we will discuss about this topic in another tutorial. If you have any questions, feel free to ask them in the comments!

Get the latest from Unaura

RSS Feed

Information

Unaura Online Systems is a business doing Web development and hosting of applications like Unra. It maintains a blog to share knowledge with people about .Net C#/Visual Basic code and financial independence.