title: C# Login form with User Authentication with SQL Server database
body: <p>I am new to SQL Server and C#. I am working on a login form that checks if the user is an admin or a basic user. In my SQL Server, I created a table that stores username, password, and role (admin or basic user). The saved data are the following: </p>
  
  <ul>
  <li>For admin: username = admin, password = admin, role = admin </li>
  <li>For basic user: username = user, password = user, role = user </li>
  </ul>
  
  <p>If the user enters username and password "admin" it should be directed to the admin page else it would be user page. </p>
  
  <p>This is my code:</p>
  
  <pre><code>string query = "SELECT * from tbl_login WHERE Username = @username and password=@password";
  
  con.Open();
  
  SqlCommand sqlcmd = new SqlCommand(query, con);
  sqlcmd.Parameters.AddWithValue("@username", tbusername.Text);
  sqlcmd.Parameters.AddWithValue("@password", tbpswlog.Text);
  DataTable dtbl = new DataTable();
  
  SqlDataAdapter sqlsda = new SqlDataAdapter(sqlcmd);
  sqlsda.Fill(dtbl);
  
  con.Close();
  
  if (dtbl.Rows.Count == 1)
  {
      this.Hide();
  
      if (tbusername.Equals("admin"))
      {
          MessageBox.Show("You are logged in as an Admin");
          AdminHome fr1 = new AdminHome();
          fr1.Show();
          this.Hide();
      }
      else
      {
          MessageBox.Show("You are logged in as a User");
          UserHome fr2 = new UserHome();
          fr2.Show();
          this.Hide();
      }
  }
  else
  {
      MessageBox.Show("Incorrect username or password");
  }
  </code></pre>
  
  <p>I know this code lacks and wrong.</p>
  
  <p>EDIT: </p>
  
  <p>I tried this code below</p>
  
  <pre><code>if (dtbl.Rows.Count == 1)
  {
      this.Hide();
  
      if (dtbl.Rows[0]["role"].ToString().Equals("admin"))
      {
          MessageBox.Show("You are logged in as an Admin");
          AdminHome fr1 = new AdminHome();
          fr1.Show();
          this.Hide();
      }
      else
      {
          MessageBox.Show("You are logged in as a User");
          UserHome fr2 = new UserHome();
          fr2.Show();
          this.Hide();
      }
  }
  else
  {
      MessageBox.Show("Incorrect username or password");
  }
  </code></pre>
  
  <p>But even if I entered username admin and password admin, it would say "You entered as a user".</p>