Multiple Forms in C#

This tutorial, you will learn how to create a program that will use mulitple forms. Basically, many programmers have many forms that are accessible from the main form that loads at start up. At this time, we’re ging to create a very simple application that has a single button. And hen this button is clicked, it loads the log in form. And this form looks like as shown below. f1 Next, we’re going to add another form. To do this, here’s 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 looks like as shown below. f2 On the second form, let’s design looks like as shown below. f3 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.
  1. Form2 loginForm;
In this code, we simply declare a variable of Type Form2. Then add this next line of code.
  1. loginForm = new Form2();
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.
  1. 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:
  1. Form2 loginForm = new Form2();
  2. 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. f4 And here’s all the code used in this application:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  10. namespace WindowsFormsApplication3
  11. {
  12. public partial class Form1 : Form
  13. {
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. }
  21. private void button1_Click(object sender, EventArgs e)
  22. {
  24. Form2 loginForm = new Form2();
  25. loginForm.Show();
  27. }
  30. }
  31. }

Add new comment