csharp

How to pass data one form to another in Windows Form

In this blog we will learn how to pass data one form to another in Windows Form.

Here Laxmikant has explained about How to pass data one form to another in Windows Form using C#.

Step 1 : Drag and drop a Label, a TextBox, a Button and a ComboBox from the Toolbox. I have created a Form with 3 Labels, a TextBox, a button and a ComboBox as shown in the following snapshot.

Step 2 : Please Click on Edit items and after that we will add items in the ComboBox as shown in the following screenshot.

Step 3 : Please write the following code in Form1.cs page.

Notes
i. I have a Name, Email and Select Hobbies label on the form. So i am using three global variables.
ii. Double-click on the Save button on the Windows Form1 and write the code.
iii. ConfirmationForm is the name of another form.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoProject
{
    public partial class Form1 : Form
    {
        //global variables
        public static string name;
        public static string email;
        public static string selectedHobbies;
       
       //ConfirmationForm  is the name of another form.
      // I have created object this form for show this form after click save button.
        ConfirmationForm confirmation = new ConfirmationForm();
        public Form1()
        {
            InitializeComponent();
        }
       //double-click on the Save button on the Windows Form1 and write the code:
        private void btnSave_Click(object sender, EventArgs e)
        {
            name = txtName.Text;
            email = txtEmail.Text;
            selectedHobbies = cmbhobbies.Text;
            this.Hide();
            confirmation.Show();
        }
    }
}

Step 4 : Add another Windows Forms form using Project –> Add Windows Form then click on Add.

Step 5 : Drag and Drop 6 Labels from the Toolbox onto ConfirmationForm.

Step 5 : Double-click on ConfirmationForm and write the code of load event:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoProject
{
    public partial class ConfirmationForm : Form
    {
        public ConfirmationForm()
        {
            InitializeComponent();
        }

        private void ConfirmationForm_Load(object sender, EventArgs e)
        {
            labelName.Text=Form1.name;
            labelEmail.Text = Form1.email;
            labelHobbies.Text = Form1.selectedHobbies;
        }
    }
}

Output

Leave a Reply

Your email address will not be published. Required fields are marked *