Wednesday, 4 April 2012

Pass Data from one form to another

To pass data from one form to another first you need to create two forms, one in which user will enter the information and second to display that information. The two forms will look something like:


Code to pass data from one form to another

//code for form 1
//code for SHOW button

//check if user has entered complete information
//if user has not entered complete information display a message to enter complete information
if (txtName.Text == "" && txtEmail.Text == "" && txtPhone.Text == "" && txtUsername.Text == "" && txtPassword.Text == "")
{
    MessageBox.Show("Enter complete information");
}
            
//if user has entered complete information
else
{
    //assign the form 1 control values to form 2 variables
    Form2.name = txtName.Text;
    Form2.phone = txtPhone.Text;
    Form2.email = txtEmail.Text;
    Form2.username = txtUsername.Text;

    //create an object of second form
    Form2 form2 = new Form2();

    //show the form by passing values
    form2.ShowDialog();

//code for form 2
public partial class Form2 : Form
{
    //declare variables 
    public static string name, email, phone, username;

    public Form2()
    {
        InitializeComponent();

        //assign the previous page values to the current page controls
        lblName.Text = name;
        lblShowPhone.Text = phone;
        lblShowUsername.Text = username;
        lblShowEmail.Text = email;
    }
}

No comments:

Post a Comment