title: using IF condition inside a while loop in C#
body: <p>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 <em>if-condition</em> inside the <em>while loop</em> but the thing is that even when the username and password are correct, it executes the <em>else-statement</em>. Please help me to solve this. </p>
  
  <p>Here is my code :</p>
  
  <pre><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())
              &amp;&amp;
              txtpass.Text==(reader["Password"].ToString())
              ) {
              //MessageBox.Show( "logged in!" );
              Home newhome=new Home();
              newhome.Show();
              this.Hide();
          }
          else {
              MessageBox.Show("Incorrect credentials!");
          }
      }
  }
  </code></pre>