0

So, I have a loginform where a user has to login to go into the mainform. I have a database with a table created to store usernames and passwords, for logging in to the application.

If the user types in the correct username and password and clicks login, it should take him/her to the mainform. This I know how to do, but how do I get the usernames and passwords from the SQL database and check if they exist, and if they exist, is it the correct username for the correct password or vice versa?

Like I said, I created a SQL database to store usernames and passwords. I then saved a user with the username and password both as "admin", just for testing purposes.

I tried this following code, but it isn't letting me log in even though I typed the correct username and password.

string username;
string password;

private void btnLogin_Click(object sender, EventArgs e)
{
    try
    {
        SqlCeConnection con = new SqlCeConnection(@"connectionString");
        SqlCeCommand com = new SqlCeCommand("SELECT username, password FROM UsersPass WHERE username = '" + txtUsername.Text + "' AND password = '" + txtPassword.Text + "'", con);
        con.Open();

    if (con.State == ConnectionState.Open)
    {
        SqlCeDataReader dtr = com.ExecuteReader();

        while (dtr.Read())
        {
            username = dtr["username"].ToString();
            password = dtr["password"].ToString();
            if (username == txtUsername.Text && password == txtPassword.Text)
            {
                Mainform frm = new Mainform();
                frm.Show();
                this.Hide();     
            }
            else
            {
                MessageBox.Show("Invalid credentials!\nPlease enter a valid username and password to continue.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
    }
    catch (Exception)
    {
        MessageBox.Show("Erorr", "Error");
    }
}

Forgive me if I'm missing something completely obvious, I'm fairly new to C#. Thank you in advance.

12
  • Use SQL parameters rather than concatenating string for SQL. And never, ever store passwords as plaintext. And if there is an exception please share the full error message. Commented Aug 8, 2016 at 15:03
  • First, read up on Sql Injection. Second, read up on encryption. Third, read up on c#'s using keyword. Commented Aug 8, 2016 at 15:03
  • You dont need if (con.State == ConnectionState.Open) If connection not open, then exception will be thrown. Commented Aug 8, 2016 at 15:03
  • I'm really not getting what you guys are saying. Like I said, I'm fairly new to C#, so I don't know most keywords and such. If you could be a little bit more specific, I would really appreciate it. Commented Aug 8, 2016 at 15:07
  • Also you don't need to read username=dtr["username"]. if(dtr.HasRows) is enough. But you need to dtr.Close(); and con.Close(). Commented Aug 8, 2016 at 15:07

2 Answers 2

1

You say you are getting the error message. Start by giving yourself more information on that. Either place a breakpoint in

catch (Exception)
{
    MessageBox.Show("Erorr", "Error");
}

so you can see some details on the exception or change it to

catch (Exception ex)
{
    MessageBox.Show("Erorr", ex.Message + Environment.NewLine + ex.StackTrace);
}

That will give you details on exactly why your application is failing and set you on a path towards getting things working like you want.

I suspect you have a bad connection string.

Edit: This particular issue was caused by sql server compact edition references being used in place of standard edition references. See the comments.

Sign up to request clarification or add additional context in comments.

6 Comments

So then, the code that I'm currently using is correct? The one that I have mentioned in my post initially. I thought that my code was completely wrong. I will re-check the connection string now. Thank you for taking the time to reply.
The way to find out if your code is "correct" or not is to see what kind of error you are actually getting in that exception. I'm guessing it's related to the connection string but I could be completely off base. Your connection string might look correct but be in the wrong format for your connection library. Just see what the exception tells you.
This is the exception I am getting. I am using the following connection string. "Data Source=DELL\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"
Are you actually using the compact edition of sql server? If you are, your connection string is targetting the wrong type of data source. If you aren't, try changing SqlCeCommand to SqlCommand, SqlCeConnection to SqlConnection, and SqlCeDataReader to SqlDataReader. Keep in mind even if that works you will get no output if you have bad credentials since you will never enter your while loop.
WOW! Changing everything to Sql instead of SclCe made it somehow work. Thank you very much, my problem is solved. Is there a way I can accept your comment as an answer?
|
0

Simply another way in that:

           private void btnLogin_Click(object sender, EventArgs e)
                    {
                        string currentUserID=string.Empty;
                        SqlConnection connection= new SqlConnection(connectionString);
                        connection.Open();
                        SqlCommand command = new SqlCommand();
                        command.CommandText = "SELECT UserID From UserPass WHERE username =@username AND password =@password";
                        command.Parameters.AddWithValue("@username", txtUsername.Text);
                        command.Parameters.AddWithValue("@password", txtPassword.Text);
                        command.Connection = connection;
                        object obj=command.ExecuteScalar();
                        if (obj!=null)
                        {
                            currentUserID= obj.ToString();
                            connection.Close();
                            Mainform frm = new Mainform();
                            frm.Show();
                            this.Hide();         
                        }
                        else
                        {
                        connection.Close();
                        MessageBox.Show("Invalid credentials!\nPlease enter a valid username and password to continue.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                    }

2 Comments

It still is not letting me log in even though I typed in the correct username and password.
I tried this code. It's working. Please check your column [email protected]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.