简体   繁体   English

在C#的while循环内使用IF条件

[英]using IF condition inside a while loop in C#

I have a problem with my C# code. 我的C#代码有问题。 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 . 我已经在C#2010中创建了一个登录表单。在验证用户名时,我在while循环内使用了if条件 但事实是,即使用户名和密码正确,它也会执行else语句 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 当您在if条件中找到用户名时,应使用中断

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. 之所以进入else块,是因为如果任何登录不正确,都会出现消息框,并且在您的代码中为n-1种情况。

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. 您需要优化SQL以仅选择该用户。 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.");
        }
    }
}

Simplest and Secure method 最简单安全的方法

 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!" );
        } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C#中使用while循环内的条件 - Using condition inside a while loop in C# While循环和条件C# - While Loop And Condition C# 如果变量在 c# 中的所述循环内更改,我如何在 while 循环的条件中包含变量 - How do I include a variable in the condition of a while loop if the variable is changed inside said loop in c# 具有 1 个以上条件/条件类型 C# 的 while 循环条件 - while loop conditions with more than 1 condition/condition type C# C#foreach内部while循环 - C# foreach inside while loop 在C#中的while循环内使用IF条件。 虚假值仍在循环 - Using IF condition inside a while loop in C#. False value still looping 如何在 C# 中正确处理异常,同时在内部使用 await 尝试在 foreach 循环中使用哪个? - How do proper exception handling in C# while using await inside try which inside foreach loop? 在 do while 循环中,我想在 c# 中每 1 分钟执行 3 次特定代码,直到满足条件 - Inside do while loop, I want to execute specific code for 3 times till condition satisfy for every 1 min in c# 条件不成立时While循环不循环C# - While Loop not looping when condition is not true C# 如果条件为真,如何在while循环中重复代码行c# - How to repeat code line if a while loop if condition is true c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM