This is my code, I need to retrieve LoginPassword
from the database
public partial class frmPassword : Form
{
SqlConnection connection = new SqlConnection(@"Data Source=WORKSTATION\SQLEXPRESS;Initial Catalog=TPSystem;Integrated Security=True");
public frmPassword()
{
InitializeComponent();
}
private void btnUpdatePassword_Click(object sender, EventArgs e)
{
frmLogin login = new frmLogin();
string UserN = login.UName;
string Pass;
SqlCommand cmd = new SqlCommand("SELECT Login_Password FROM AdminLogin WHERE Login_Username = '"+UserN+"'", connection);
try
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
Pass = reader["Login_Password"].ToString();
if (tbOldPassword.Text == Pass)
MessageBox.Show("Password matches");
else
MessageBox.Show("Password wrong");
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "Report", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
}
I got this error on execution:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: Invalid attempt to read when no data is present.
The reader.Read()
methods returns a boolean to indicate if anything was in fact read - you're not checking that at all....
Change your code to:
if(reader.Read())
{
Pass = reader["Login_Password"].ToString();
if (tbOldPassword.Text == Pass)
MessageBox.Show("Password matches");
else
MessageBox.Show("Password wrong");
}
If nothing was read, I guess your user doesn't exist - I'm not sure what you want to do in that case.... up to you
But please tell me you're NOT storing passwords in clear text in your database!!!!
It seems that there is no entry in the database for the username you are checking. Please check if thereader returns a result:
public partial class frmPassword : Form
{
SqlConnection connection = new SqlConnection(@"Data Source=WORKSTATION\SQLEXPRESS;Initial Catalog=TPSystem;Integrated Security=True");
public frmPassword()
{
InitializeComponent();
}
private void btnUpdatePassword_Click(object sender, EventArgs e)
{
frmLogin login = new frmLogin();
string UserN = login.UName;
string Pass;
SqlCommand cmd = new SqlCommand("SELECT Login_Password FROM AdminLogin WHERE Login_Username = '"+UserN+"'", connection);
try
{
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Pass = reader["Login_Password"].ToString();
if (tbOldPassword.Text == Pass)
MessageBox.Show("Password matches");
else
MessageBox.Show("Password wrong");
}
reader.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "Report", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.