Click here to Skip to main content
16,017,881 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi, I want to compare username and password from my textfield values with the one in datatable. I am using a loop but the problem is each time the loop will compare every single data in the table. For example, if I enter "ABC" as username and "123" as password which is contain inside the datatable but at 2nd row, the system will even compare the 1st row of record and return me some message. So how can i just compare or determine the username and password i enter is correct without having to loop from the beginning of the table? Below are my codes:


C#
<pre lang="c#">DataTable dt = new DataTable("UserInfo");
            OleDbDataAdapter da = new OleDbDataAdapter();
            OleDbConnection oledbconnection = new OleDbConnection();
            OleDbCommand oledbcommand = new OleDbCommand();

            try
            {
                oledbconnection.ConnectionString = "Provider=VFPOLEDB.1;Data Source=" + Convert.ToString(ConfigurationManager.AppSettings["DBFFolder"]) + ";";
                oledbconnection.Open();
                oledbcommand.CommandType = CommandType.Text;
                oledbcommand.CommandText = "Select * from SHRMSUSR";
                oledbcommand.Connection = oledbconnection;

                da.SelectCommand = oledbcommand;
                da.Fill(dt);

                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        var EncryptedString = row["Encrypted"].ToString();
                        username = txtUsername.Text;
                        password = txtPassword.Text;

                        usernameDB = stringDecrypt(EncryptedString.Substring(4, 10), "HRM");
                        passwordDB = stringDecrypt(EncryptedString.Substring(84, 10), "HRM");

                        if (username.Equals(usernameDB)) 
                        {
                            if (password.Equals(passwordDB))
                            {
                                ExportToExcel excel = new ExportToExcel();
                                this.Hide();
                                excel.Show();
                                break;                              
                            }
                        }
                        else
                            MessageBox.Show("Incorrect Username or Password\n\nPlease reenter !", "Error !!!");
                        
                    }
                }
                else
                {
                    ResponseCode = "APPLICATION_ACCESS_ISSUE";
                    ResponseCodeDesc = "No records retrieved";
                }
            }
            catch (Exception ex)
            {
                ResponseCode = "APPLICATION_UNAVAILABLE";
                ResponseCodeDesc = ex.Message.ToString();
            }<pre lang="c#">
Posted
Updated 15-May-14 18:24pm
v2

You do have a break which should get you out of the loop. However, what you should do is narrow down the search to begin with so you aren't returning all rows to your code from the database.

Do something more like:

C#
oledbcommand.CommandText = "Select * from SHRMSUSR WHERE username = @username AND password = @password";
oledbcommand.Parameters.AddWithValue("@username", usernameDB);
oledbcommand.Parameters.AddWithValue("@password", passwordDB);

OleDbDataReader dr = oledbcommand.ExecuteReader();
if (dr.HasRows)
{
  // this means it found a record
}


http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.aspx[^]
 
Share this answer
 
Comments
Jamie888 15-May-14 21:57pm    
yes, but if i have to decrypt the username and password(which was encrypted) in database after i have retrieved them. How can i use a datareader to read the datatable(which contains all the record i fetched from database)?
ZurdoDev 15-May-14 22:02pm    
Sorry. I looked over the part where you were decrypting in C#. I don't like that approach but that may be how you have to do that.

To iterate over records in a datareader you can simply do

while (dr.Read())
{

}
Jamie888 15-May-14 22:05pm    
does it means that i hav to write as following:?
OleDbDataReader dr = datatable1.ExecuteReader();
while(dr.Read())
{
if(dr.HasRows)
{
}
}
ZurdoDev 15-May-14 22:10pm    
Other way around.

if (dr.HasRows)
{
while (dr.Read())
{

}
}
Jamie888 15-May-14 22:18pm    
my decrypted username and password has been passed into datatable. How can i read the datatable by using datareader and the hasRows function?
Encrypting and then decrypting password does not make sense and is unnecessarily dangerous. You should never store any passwords anywhere, it is not needed for authentication. Instead, you can store cryptographic hash function of a password and compare hash with hash.
Please see my past answers for further detail:
i already encrypt my password but when i log in it gives me an error. how can decrypte it[^],
Decryption of Encrypted Password[^],
storing password value int sql server with secure way[^].

—SA
 
Share this answer
 
C#
public bool isAuthenticated(string userID, string password)
        {
            if (conn.State.ToString() == "Closed")
            {
                conn.Open();
            }
            SqlCommand newCmd = conn.CreateCommand();
            newCmd.Connection = conn;
            newCmd.CommandType = CommandType.Text;
            newCmd.CommandText = "SELECT [UserID]  ,[Department] ,[UserName] ,[Password] ,[Active] FROM [Traveller].[dbo].[User_Details] where [UserID]= '" + userID + "' and [Password]= '" + Security.Encrypt(password) + "'";

            SqlDataReader dr = newCmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    UserInfo ui = new UserInfo(dr["UserID"].ToString(), dr["UserName"].ToString());
                }
                newCmd.Dispose();
                conn.Close();
                return true;
            }
            else
            {
                newCmd.Dispose();
                conn.Close();
                return false;
            }


        }

-----------------------------------------------------------------------------
-----------------------------------------------------------------------------

C#
class UserInfo
    {
        private static string _userId;
        private static string _fullName;
        public UserInfo(string userId ,string fullName)
        {
            _userId = userId;
            _fullName = fullName;
        }

        public UserInfo()
        {

        }

        public string UserId
        {
            get
            {
                return _userId;
            }
        }
        public string FullName()
        {
            return _fullName;
        }

        public string userID()
        {
            return _userId;
        }

    }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900