Shevliaskovic Shevliaskovic - 2 months ago 6
C# Question

C# Database Log In form

I want to create a Registration and Log In form on Visual Studio 2010 (with Visual C#).

I have created Service-Based Database and one table. I can insert data into the table (at the registration form), but I cannot figure out how to log in the user.

I have a very simple Log In Form (just fields for username and password) and a 'Log In' Button. I do not really know how to check if the password and the username (that exist in my database) match. Here is what I have so far:

private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "" & textBox2.Text != "")
{
cn.Open(); // cn is the Sqlconnection
cmd.Parameters.AddWithValue("@Username", textBox1.Text); // cmd is SqlCommand
cmd.Parameters.AddWithValue("@Password", textBox2.Text);
if (cmd.CommandText == "SELECT * FROM Table1 WHERE username = @Username AND password = @Password")
{
MessageBox.Show("Loggen In!");
this.Close();
}
cn.Close();
}
}

Answer

You need to Execute the query to know if the information exists in the database

 if (textBox1.Text != "" & textBox2.Text != "")  
   {  
        string queryText = @"SELECT Count(*) FROM Table1 
                             WHERE username = @Username AND password = @Password";
        using(SqlConnection cn = new SqlConnection("your_connection_string"))
        using(SqlCommand cmd = new SqlCommand(queryText, cn))
        {
            cn.Open();  
            cmd.Parameters.AddWithValue("@Username", textBox1.Text); 
            cmd.Parameters.AddWithValue("@Password", textBox2.Text);  
            int result = (int)cmd.ExecuteScalar();
            if (result > 0)  
                MessageBox.Show("Loggen In!");  
            else
                MessageBox.Show("User Not Found!");  
        }
    }  

I have also changed something in your code.

  • Changed the query text to return just the count of the users with the specific username and account and be able to use ExecuteScalar
  • Enclosed the creation of the SqlConnection and SqlCommand in a using statement to be sure to dispose these objects at the end of the operation

I also recommend to change the the way in which you store the password.
Store, in the password field, an hash not the clear password. Then pass to the database the same hash and compare this against the content of the database field.
In this way, the password is known only to your user, not by you or by any passersby that looks at the database table