data reader issues
im new to c# and trying to make a simple login page. it doesnt seems to extract the pwd fromt he db. it makes hte if(DR.Read()) check alright but the out put i get is invalid password. so it runs the name check but the pass check doesnt go through.
void Login_Click(Object Src, EventArgs E) {
string strConn = "Provider=SQLOLEDB; server=localhost; user id=#; password=#; database=LoginTest;";
OleDbConnection Conn = new OleDbConnection(strConn);
Conn.Open();
string strSQL = "SELECT U_Password FROM TblUser WHERE U_Name = '" + txtUname.Text + "'";
OleDbCommand Cmd = new OleDbCommand(strSQL, Conn);
OleDbDataReader Dr = Cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (Dr.Read())
{ i
f (Dr["U_Password"].ToString() == txtPwd.Text) {
FormsAuthentication.RedirectFromLoginPage(txtUname.Text, false);
}
else
{
lblLoginMsg.Text = "Invalid password.";
}
}
else
{
lblLoginMsg.Text = "Login name not found."; Dr.Close(); }
}
[1040 byte] By [
false420] at [2007-12-16]
> if (Dr.Read())
> {
> if (Dr["U_Password"].ToString() == txtPwd.Text) { is ToString overloaded there? Otherwise, you're getting the object type. If it isn't overloaded, you can cast:
(string)Dr["U_Password"]
ok some diagnostics
If you want to only pull one value from the statment you execute on the database you can use ExecuteScalar() method on the OleDbCommand object (it too returns a object that needs to be casted back into string).
You can alternatively use OleDbDataReader's GetString(0) method to get the string value at zero index. When you use this method you do not need to perform a typecast.
you refine your code to
if( Dr.Read() )
{
string pass = Dr.GetString(0) ;
if( pass == txtPass.Text )
{
...........
}
}
put a break point on the line which assigns the password to the variable pass. And check the value that's returned from the database while debugging.
Also check there is no duplicate usernames in the database and that the username has a password.
Regards,
Saurabh Nandu
www.MasterCSharp.com