C#C
C#3y ago
yumo

❔ login system saves data from user

Hi this is the code that i have and i dont know why but its showing me the username and not the realname on the label, why?

Button on Form1 to check if user credentials are correct and if user exists open MainMenu and display the realname of the user logged in.
private void btnEntrar_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=(localdb)\\MSSqlLocalDB;Initial Catalog=oil;Integrated Security=True;Pooling=False";
            string username = txtUsername.Text;
            string password = txtPassword.Text;
            UserData loggedInUser = null;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                SqlCommand command = new SqlCommand("SELECT * FROM Users WHERE username = @username AND password = @password", connection);
                command.Parameters.AddWithValue("@username", username);
                command.Parameters.AddWithValue("@password", password);

                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();
                    int id = reader.GetInt32(0);
                    string realname = reader.GetString(1);
                    string nivel = reader.GetString(2);

                    // create a new User object with the retrieved data
                    loggedInUser = new UserData(id, realname, nivel);

                    // open the main menu form
                    MainMenu mainMenu = new MainMenu(loggedInUser);
                    mainMenu.Show();
                    this.Hide();
                }
                else
                {
                    // invalid credentials, display error message
                    MessageBox.Show("Credenciais inválidas!");
                }

                reader.Close();
            }
        }
Was this page helpful?