18 December, 2014

How to pass value from one Winform to another Winform in c#

Suppose we have to pass value from LoginPage.cs to HomePage.cs like Username & Role (whatever as per requirement)

Here the simplest code for it :

1) LoginPage.cs

on btnLogin Click :

[ write your code to connect the user with database and if user is valid ... ]

private void btnLogin_Click(object sender, EventArgs e)
        {
            using (SqlConnection con = new SqlConnection(CS))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand("Select * from Users where Username='" + txtUsername.Text + "' and Password='" + txtPassword.Text + "'", con);
                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    this.Hide();
                    HomePage frm = new HomePage();
                    frm.UserName = txtUsername.Text;
                    frm.Show();
                }
                else
                {
                    MessageBox.Show("Username or Password incorrect", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
        }

2) HomePage.cs

You have to declare / initialize some public string ... like

public HomePage()
        {
            InitializeComponent();
        }

        public string UserName;
        private void HomePage_Load(object sender, EventArgs e)
        {
           
            lblUserName.Text = UserName;
        }


that's it;
on LoginPage's btnLogin button click it will save/pass values to HomePage.cs public string... and that values will be send to HomePage.cs [call it on HomePage.cs Load Event].

No comments:

Post a Comment