Search code examples
c#datareader

DataReader does not read my if code


I have a login winform and i put Change Password in it. I have this code for updating my password info in my database. But it does not read my datareader if it is in true, but if it is in false it will read it, and change the password in my database.

    public void ChangePass()
    {
        sc.Open();
        try
        {
            if (_oldpass == "" || _newpass == "" || _conpass == "")
            {
                string message = "Must fill up all the fields!";
                string title = "Voting System Error Message";
                MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                cmd = new SqlCommand("SELECT password FROM TableLogin WHERE password = '" + _oldpass + "'", sc);

                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read() == true)
                {
                    sc.Close();
                    if (_newpass == _conpass)
                    {
                        sc.Open();
                        cmd = new SqlCommand("UPDATE TableLogin SET password = '" + _newpass + "' WHERE username = 'admin'", sc);

                        SqlDataReader sdr = cmd.ExecuteReader();
                        if (sdr.Read() == true) 
                        {
                            MessageBox.Show("Successfully Changed!"); 
//This part does not read if true.. but if sdr.Read() == false it changes the password from my database.
                        }
                    }
                    else
                    {
                        string message = "New Password and Confirm Password does not match!";
                        string title = "Voting System Error Message";

                        MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    string message = "Wrong Old Password!";
                    string title = "Voting System Error Message";

                    MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sc.Close();
        }
    }

I don't understand, why?


Solution

  • I suppose Update statement in sql will not return records so read will not return true. You should use ExecuteNonQuery instead.

    if (cmd.ExecuteNonQuery() > 0) 
    {
        MessageBox.Show("Successfully Changed!"); 
    }
    

    BTW as pointed in comments use parameterized queries to prevent sql injection.