简体   繁体   中英

How to show username on the welcome page

I have two forms Form1 and Form2. Form1 contains two textBoxs for login details and Form2 contain a label just to show the username. I have this code but it doesn't work. Thanks in advance.

Form1

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string constring = @"Data Source=.;Initial Catalog=POS;Integrated Security=True";
        SqlConnection con = new SqlConnection(constring);
        con.Open();
        SqlCommand sqlcmd = new SqlCommand("Select firstname, password from credentials", con);
        SqlDataReader dr = sqlcmd.ExecuteReader();

        while (dr.Read())
        {
            string username = usernametxt.Text;
            string password = passwordtxt.Text;
            if (dr["username"].ToString() == username && dr["password"].ToString() == password)
            {
                Form2 hmpage = new Form2(username);

                hmpage.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("The username or password you entered is incorrect!", "Logon Message!");
            }
        }
        con.Close();
        dr.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Form2

public Form2(string strTextBox)
{
    InitializeComponent();
    label1.Text = "Welcome to:(" + strTextBox + ")";
}

It would be better if you add breakpoints to some statements of your code for you to trace why it doesn't work. (press F5.. then F11 after adding breakpoints).

By then, you can add global variable, which can reside at Program.cs and assign the retrieved username.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM