Multiple Forms in C#

June 14, 2020
C#
c# multiple forms in same window

In this tutorial, you will learn how to create a program that will use multiple forms. Many programmers have many ways that are accessible from the main structure that loads at startup. At this time, we’re going to create a straightforward application that has a single button. And hen this button is clicked, it loads the login form. And this form looks like as shown below.

multiple forms in c#

Next, we’re going to add another form. To do this, here are the following steps:
1. Go to Solution Explorer
2.Right-click project and select Add
3. Then Choose “Windows Form”
4. And it will automatically add a new form to your project.
The following steps look like, as shown below.

multiple forms in c#

On the second form, let’s design looks like as shown below.

multiple forms in c#

Next, let’s go back to our Form1 which is the first form that loads at start up.then double click the “Login” button and add the following code.

Form2 loginForm;

this code, we simply declare a variable of Type Form2. Then add this next line of code.

this next line of code, we create a new object. And if you prefer to shorten this two line of code, to make it in a single line. Here’s the following code.

this next line of code, we create a new object. And if you prefer to shorten this two line of code, to make it in a single line. Here’s the following code.

Form2 loginForm = new Form2();

Next, to get the login form to appear, you can use the method of the object called “Show()”. So the code now should look like this:

Form2 loginForm = new Form2();
loginForm.Show();

at this time, let’s run the application and test it out. Click the “Login” button and the login form should appear. And this look like as shown below.

multiple forms in c#

And here’s all the code used in this application:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
 
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
 
            Form2 loginForm = new Form2();
            loginForm.Show();
 
        }
 
 
    }
}
Facebook Comments

Leave a Reply

Your email address will not be published.