Introduction
In this article, I describe how to pass data from one form to another form in a Windows application using C#. When we encounter the requirement to use the first page's controls data on a second page in a Windows application it sometimes becomes difficult. Today I explore the possible ways to send the data from one page to another page in C# Windows application using a class.
Form1 description
In From1 we use two textboxes and two buttons. On button1 click first, we validate to ensure that the textboxes are not blank, calling the second form and saving the value of the textboxes in a variable declared in a class.
- 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 WindowsFormsApplication1 {
- public partial class Form1: Form {
- public Form1() {
- InitializeComponent();
- }
- private void button2_Click(object sender, EventArgs e) {
- this.Close();
- }
- private void button1_Click(object sender, EventArgs e) {
- if (textBox1.Text == "" || textBox2.Text == "") {
- MessageBox.Show("please don't leave any textbox is empty");
- } else {
- Class1.name = textBox1.Text;
- Class1.address = textBox2.Text;
- Form2 ob = new Form2();
- ob.Show();
- }
- }
- }
- }
Form2 description
In this form, we use two textboxes in which the values are displayed in Form1. We use one button for closing the Form2.
On the Form Load event, we define the coding of transferring the value in textbox1 and textbox2. On the button click event define the code for closing the 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 WindowsFormsApplication1 {
- public partial class Form2: Form {
- public Form2() {
- InitializeComponent();
- }
- private void Form2_Load(object sender, EventArgs e) {
- textBox1.Text = Class1.name;
- textBox2.Text = Class1.address;
- }
- private void button1_Click(object sender, EventArgs e) {
- this.Close();
- }
- }
- }
Class description
In this class, we use two static string variables and create two static functions to set and get the value of these two variables.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace WindowsFormsApplication {
- class Class1 {
- static string nm, add;
- public static string name {
- get {
- return nm;
- }
- set {
- nm = value;
- }
- }
- public static string address {
- get {
- return add;
-
- }
- set {
- add = value;
- }
- }
- }
- }
Output