簡體   English   中英

在C#的while循環內使用IF條件

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

我的C#代碼有問題。 我已經在C#2010中創建了一個登錄表單。在驗證用戶名時,我在while循環內使用了if條件 但事實是,即使用戶名和密碼正確,它也會執行else語句 請幫我解決這個問題。

這是我的代碼:

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

當您在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..!");

之所以進入else塊,是因為如果任何登錄不正確,都會出現消息框,並且在您的代碼中為n-1種情況。

您正在檢查所有用戶的用戶名和密碼是否相同。 您需要優化SQL以僅選擇該用戶。 另外,為了您的用戶,請閱讀密碼哈希。

因為它是一個循環。

創建一個布爾變量。 循環更新其值(如果找到相同的用戶名和密碼),並根據其值檢查外部。

做這個

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 + "'"

我將以這種方式解決:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM