Login Code works for admin and user , but did not show error when login with wrong id or pass

StackOverflow https://stackoverflow.com/questions/20484767

  •  30-08-2022
  •  | 
  •  

Question

I am creating a program for my final project , i have set-up a database , everything works fine , but the only thing i couldn't finish is the Login system.

Both Users and admin will log through the same form.

When i enter an admin id , it will login and say "hello admin" , and user the same. but when i enter a non-existent id , it wouldn't show the error..

here's my code -

private void button1_Click(object sender, EventArgs e)
{
try
{
    string userNameText = txtUser.Text;
    string passwordText = txtPass.Text;
    string isAdmin = "yes";
    string isNotAdmin = "no";
    if (!(string.IsNullOrEmpty(txtUser.Text)) && !(string.IsNullOrEmpty(txtPass.Text)))
    {
        SqlConnection SCScon = new SqlConnection();
        SCScon.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
        SqlCommand cmd = new SqlCommand("SELECT ISNULL(SCSID, '') AS SCSID, ISNULL(SCSPass,'') AS SCSPass, ISNULL(isAdmin,'') AS isAdmin FROM SCSID WHERE SCSID='" + txtUser.Text + "' and SCSPass='" + txtPass.Text + "'", SCScon);
        SCScon.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
                {
                    if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
                        this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
                        this.CompareStrings(dr["isAdmin"].ToString(), isAdmin))
                    {
                        MessageBox.Show("Hello " +txtUser.Text , "Admin" , MessageBoxButtons.OK , MessageBoxIcon.Information);
                        _Adminform.Show();
                        this.Hide();
                    }
                    else if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
                        this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
                        this.CompareStrings(dr["isAdmin"].ToString(), isNotAdmin))
                    {
                        MessageBox.Show("Welcome " + txtUser.Text , "User");
                        _userform.Show();
                        this.Hide();

                    }
                    else
                    {
                        MessageBox.Show("Wrong ID/Pass");
                    }

                }'
    }
}
catch (Exception ex)
        {
            MessageBox.Show("error2" + ex);
        }

}

Était-ce utile?

La solution

Problem : You are checking for invalid user inside the whle loop. loop enters when only required user is matched. so if invalid user credentials are given it will not enter the loop hence you could not see the Invalid User MessageBox.

Solution : you can check the dr.Read() return value, if it is true means it has row with the user (either admin or normal-user).

if(dr.Read())
{
                if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
                    this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
                    this.CompareStrings(dr["isAdmin"].ToString(), isAdmin))
                {
                    MessageBox.Show("Hello " +txtUser.Text , "Admin" , MessageBoxButtons.OK , MessageBoxIcon.Information);
                    _Adminform.Show();
                    this.Hide();
                }
                else if (this.CompareStrings(dr["SCSID"].ToString(), txtUser.Text) &&
                    this.CompareStrings(dr["SCSPass"].ToString(), txtPass.Text) &&
                    this.CompareStrings(dr["isAdmin"].ToString(), isNotAdmin))
                {
                    MessageBox.Show("Welcome " + txtUser.Text , "User");
                    _userform.Show();
                    this.Hide();

                }
}
else
{
 MessageBox.Show("Wrong ID/Pass");
}

Autres conseils

if the User name and password does not match, the line SqlDataReader dr = cmd.ExecuteReader(); returns no rows, so it will not enter the while(dr.Read()) and hence, will not enter the else inside while(dr.Read()).

You will need to put the MessageBox.Show("Wrong ID/Pass"); outside the while loop.

This is the code inside the form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace LoginDialogForm
{
    public partial class Login_Dialog_Form1 : Form
    {
        public Login_Dialog_Form1()
        {
            InitializeComponent();
        }
        private bool ValidateUsername()
        {
            //TODO: add code to validate User Name.
            return true;
        }
        private bool ValidatePassword()
        {
            if (!ValidateUsername())
            {
                MessageBox.Show("Wrong Username", "Invalid Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            else
            {
                //TODO: add code to validate password.
                if (false)
                {
                    MessageBox.Show("Wrong Password", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
                else
                    return true;
            }
        }
    }
    private void btnOk_Click(object sender, EventArgs e)
    {
        if (!ValidatePassword())
        {
            txtUserName.Clear();
            txtPassword.Clear();
            return;
        }
        else
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        txtUserName.Clear();
        txtPassword.Clear();
        this.Close();
    }
}

This the controls and their relevant properties:

//
// btnOk
//
Name = "btnOk";
Text = "&Ok";
btnOk.Click += new System.EventHandler(this.btnOk_Click);
//
// btnCancel
//
DialogResult = System.Windows.Forms.DialogResult.Cancel;
Name = "btnCancel";
Text = "&Cancel";
btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// txtUserName
//
Name = "txtUserName";
//
// txtPassword
//
PasswordChar = '*';
Name = "txtPassword";
//
// label1
//
Name = "label1";
Text = "Username";
//
// label2
//
Name = "label2";
Text = "Password";
//
// LogoPictureBox
//
LogoPictureBox.Name = "LogoPictureBox";
LogoPictureBox.TabStop = false;
//
// LoginForm1
//
AcceptButton = this.btnOk;
CancelButton = this.btnCancel;
ControlBox = false;
FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
Name = "LoginForm1";
ShowInTaskbar = false;
StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
Text = "Login Form";

This the code to call the form:

private void Form1_Load(object sender, EventArgs e)
{
    Login_Dialog_Form1 NewLogin = new Login_Dialog_Form1();
    DialogResult Result = NewLogin.ShowDialog();
    switch (Result)
    {
    case DialogResult.OK:
        //do stuff
        break;
    case DialogResult.Cancel:
        this.Close();
        break;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top