0

I have been trying to figure out why I am getting this error message and it's driving me up the wall cause I think I have applied all that is needed to get the result I desire. What can I do to accomplish this.

private void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            // Receive user input from login screen
            string username = txtUsername.Text;
            string password = txtPassword.Text;

            // Test if user input is null or white space aka empty
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                MessageBox.Show("Please enter both username and password");
            else
            {
                // Establish connection with database
                SqlConnection cn = new SqlConnection(@"SERVER=KACY-PC\SQLEXPRESS2014;DATABASE=hardwareMgmt;Integrated Security=True");
                cn.Open();

                SqlCommand cmd = new SqlCommand();
                cmd.Connection = cn;

                string strSQL = "SELECT * FROM tbl_user WHERE username = '" + username + "' AND password = '" + password + "'";
                cmd.CommandText = strSQL;

                SqlDataReader dr = cmd.ExecuteReader();

                // Count number of record
                int count = 0;
                while (dr.Read())
                    count += 1; MessageBox.Show(Convert.ToString(count));
                dr.Read();

                // Validate whether user has logged in before and display appropriate 
                if (count == 1 && dr["first_login"].ToString() == "N")
                    MessageBox.Show("Welcome back '" + dr["first_name"].ToString() + "' '" + dr["last_name"].ToString() + "'", "Welcome back", MessageBoxButtons.OK);
                else if (count == 1 && dr["first_login"].ToString() == "Y")
                    MessageBox.Show("Hello " + dr["first_name"].ToString() + "' '" + dr["last_name"].ToString() +
                        "\nIt appears that you are logging in for the first time" +
                        "\nor your password got reset", "Welcome", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else if (count > 1)
                    MessageBox.Show("Duplication in user account \nPlease contact System Administrator", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show("Invalid Username or Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

I Keep getting the following result after I enter the credentials in the login window. I am sure that the record is found in the database but it just not reading it.

This is the error message I am getting after I login

Kefash
  • 523
  • 2
  • 10
  • 24
  • Yes I'm sure it returns data. I have checked the database and even printed out the record count as stated in the code above. Additionally, I am just doing this for a school assignment that is due tomorrow. But sure, I would also like to know what you have in mind to mitigate against SQL Injection. – Kefash Nov 15 '15 at 15:56

1 Answers1

3

Your

dr.Read();

line is unnecessary since after your

while (dr.Read())
    count += 1; MessageBox.Show(Convert.ToString(count));

code, there will be no next record to read, that's why you get this error.

As Ivan commented, you can not read any data after your while. That's why, whatever wanna read first_login, first_name, last_name etc.. columns, you have to read while you iterating your reader. That's why consider to change your logic first.

And for myself, I prefer to use GetXXX methods of SqlDataReader when I wanna read the values instead of dr[...] syntax. That makes more readable in my opinion.

A few things more;

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 1
    +1 Just for the record, removing the unnecessary line would not help because he'll start getting another exceptions of `dr[..]` statements. The whole logic is wrong. – Ivan Stoev Nov 15 '15 at 15:58
  • @IvanStoev Right. I updated my answer based on your comment. Thank you. – Soner Gönül Nov 15 '15 at 16:04
  • Thanks this really helped. I must first say that I didn't get teaching at all in class. I have applied all of the above. `parameterized query`, `using statements` and re worked the logic so that the needed fields are captured during the `while (dr.read())`. The only thing I have not applied is not storing the password in the database as plain text. The reason is because its not really a requirement for this school assignment. – Kefash Nov 16 '15 at 01:08
  • also I didn't employ the GetXXX methods of SqlDataReader because I didn't really understand how apply the concept. – Kefash Nov 16 '15 at 01:11