简体   繁体   中英

using IF condition inside a while loop in C#

I have a problem with my C# code. I have created a login form in C# 2010. When I am validating the user name, I used an if-condition inside the while loop but the thing is that even when the username and password are correct, it executes the else-statement . Please help me to solve this.

Here is my code :

private void btnlogin_Click(object sender, EventArgs e) {
    string connection=
        @"Data Source=.\SQLEXPRESS;" 
        +" AttachDbFilename=|DataDirectory|ResturantDB.mdf;"
        +" Integrated Security=True; User Instance=True";

    SqlConnection cn=new SqlConnection(connection);

    try {
        cn.Open();
    }
    catch(Exception) {
        // print the exception's message?
        MessageBox.Show("Connection to Database failed; check Connection!");
    }

    SqlCommand cmd=new SqlCommand("SELECT * FROM [Login]", cn);
    cmd.Connection=cn;
    SqlDataReader reader=null;
    reader=cmd.ExecuteReader();

    while(reader.Read()) {
        if(
            txtuser.Text==(reader["Username"].ToString())
            &&
            txtpass.Text==(reader["Password"].ToString())
            ) {
            //MessageBox.Show( "logged in!" );
            Home newhome=new Home();
            newhome.Show();
            this.Hide();
        }
        else {
            MessageBox.Show("Incorrect credentials!");
        }
    }
}

you should use a break, when a username is found in your if condition like

bool found = false;
while (reader.Read())
{   
  if (txtuser.Text == (reader["Username"].ToString()) && txtpass.Text == (reader["Password"].ToString()))
  {
    //MessageBox.Show("loged in!");
    Home newhome = new Home();
    newhome.Show();              
    this.Hide();
    found = true;
    break;
  }
}

if (!found)
    MessageBox.Show("Incorrect credentian..!");

you get into the else block because if any login is not correct, the messagebox appears and that is in n-1 cases in your code.

You're checking if all users have the same user name and password. You need to refine your SQL to select only that one user. Also, please read into password hashing for the sake of your users.

Because its in a loop.

create a bool variable. update its value in loop (if found same username and password) and check outside based on its value.

Do this

bool found;
while (reader.Read())
{
    if (txtuser.Text == (reader["Username"].ToString()) && 
        txtpass.Text == (reader["Password"].ToString()))
    {
        found = true;
        break;
    }                
}
if (found)
{
    MessageBox.Show("loged in!");
    Home newhome = new Home();
    newhome.Show();

    this.Hide();
}
else
{
    MessageBox.Show("Incorrect credentian..!");
}

无需遍历您的案例的记录,使用此查询,在查询中计算用户名和密码即可:

"SELECT * FROM [Login] where Username='" + txtuser.Text "' and password = '"  + txtpass.Text + "'"

I will solve it on this way:

private void btnlogin_Click(object sender, EventArgs e)
{
    string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ResturantDB.mdf;Integrated Security=True;User Instance=True";
    SqlConnection cn = new SqlConnection(connection);
    try
    {
        cn.Open();
    }
    catch (Exception)
    {
        MessageBox.Show("Conncetion to Database faild check Connection !");
    }

    while (true)
    {
        SqlCommand cmd = new SqlCommand("SELECT [Password] FROM [Login] WHERE [Username] = '" + txtuser.Text + "'", cn);
        cmd.Connection = cn;
        SqlDataReader reader = null;
        reader = cmd.ExecuteReader();

        if (!reader.HasRows)
            MessageBox.Show("User does not exist. Please, try again.");
        else
        {
            //username should be unique, so only one row is possible to have
            reader.Read();
            if (txtpass.Text == (reader["Password"].ToString()))
                {
                    //MessageBox.Show("loged in!");
                    Home newhome = new Home();
                    newhome.Show();

                    this.Hide();
                    return;
                }
            else
                    MessageBox.Show("Incorrect credentian..! Try again.");
        }
    }
}

 SqlCommand cmd = new SqlCommand("Select uname, pswd from [Login] where uname =@uname and pswd =@ps", conn);
        cmd.Parameters.Add(new SqlParameter("@uname", "username here"));
        cmd.Parameters.Add(new SqlParameter("@ps", "pasword here"));            
        SqlDataReader reader = cmd.ExecuteReader();
        if (reader.Read()) 
        {
             //MessageBox.Show( "logged in!" );
            Home newhome = new Home();
            newhome.Show();

            this.Hide();

        }
        else
        {
            MessageBox.Show( "Incorrect credentials!" );
        } 

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