hi everyone
i want a solution for this. i tried to check a all data from datbase table using dataset with a foreach loop. but this logic check only first row not below that so any one help me to solve this problem so i can check all rows from table
code is like

con = new System.Data.SqlClient.SqlConnection();
            da = new System.Data.SqlClient.SqlDataAdapter();
            ds1 = new DataSet();

            con.ConnectionString ="Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\Visual Studio 2008\\Projects\\OnlineTest\\OnlineTest\\App_Data\\Test.mdf;Integrated Security=True;User Instance=True";
            con.Open();

            String sql = "SELECT * FROM UserNew";
            da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
            da.Fill(ds1, "UserNew");
           
            foreach (DataRow myRow in ds1.Tables[0].Rows)
            {
                if (Convert.ToString(myRow[i]["u_name"]) == uname && Convert.ToString(myRow["u_pass"]) == upass)
                {
                    return true;
                }
                else
                    return false;
                i++;

            }
            return false;
            con.Close();
        }

Dani AI

Generated

Quick diagnosis: two bugs are stopping you. Returning from inside the foreach (either return true or return false) makes the method exit on the first row, so only the first row ever gets checked. The indexing error comes from using myRow[i]["u_name"]: myRow[i] is an object, not a DataRow, so you cannot index it again. The i++ is unnecessary with foreach, and con.Close() after a return is unreachable. and were on the right track — remove the early return false and use parameterized SQL — below are concrete fixes and safer alternatives.

A recommended, simple and safe approach is to let SQL do the match and return whether a record exists (avoids row-by-row loops and is SQL‑injection safe):

using (var con = new System.Data.SqlClient.SqlConnection(connString))
using (var cmd = con.CreateCommand())
{
    cmd.CommandText = "SELECT COUNT(1) FROM UserNew WHERE u_name = @u AND u_pass = @p";
    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@u", System.Data.SqlDbType.NVarChar, 100) { Value = uname ?? (object)DBNull.Value });
    cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@p", System.Data.SqlDbType.NVarChar, 100) { Value = upass ?? (object)DBNull.Value });
    con.Open();
    int matches = (int)cmd.ExecuteScalar();
    return matches > 0;
}

If you must iterate a DataSet (debugging or legacy code), use foreach (DataRow row in table.Rows) and read columns safely with row.Field<string>("u_name") (handles DBNull), trim/normalize values before comparing, and only return true when you find a match; after the loop return false. Always wrap connections/commands in using so they are closed even on exceptions.

Security notes and quick checks: do not store plain-text passwords — store a salted hash (PBKDF2/bcrypt/Argon2) and compare hashes. Use parameterized commands to prevent injection. When debugging, verify ds.Tables.Count and ds.Tables[0].Rows.Count, and set a breakpoint inside the loop to inspect values and nulls.

Recommended Answers

All 4 Replies

Remove else part.

...
 foreach (DataRow myRow in ds1.Tables[0].Rows)
            {
                if (Convert.ToString(myRow[i]["u_name"]) == uname && Convert.ToString(myRow["u_pass"]) == upass)
                {
                    return true;
                }
                i++;

            }
            return 
...

hay sorry but this not working
if (Convert.ToString(myRow["u_name"]) == uname
it give error
Error 1 Cannot apply indexing with [] to an expression of type 'object'
why this?

...
 foreach (DataRow myRow in ds1.Tables[0].Rows)
  {
  if (myRow["u_name"].ToString()== uname && myRow["u_pass"].ToString() == upass)
          {
             return true;
          }
   i++;
  }
 
...

Is there any reason why you aren't checking the username directly in your SQL query instead of iterating through the user table?

// don't ever do this!
String sql = "SELECT * FROM UserNew WHERE u_name = '" + uname + "'";

Ideally you should be doing this using the SQL Command, SqlParameter and SQLDataReader methods to prevent injection attacks.

SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand("select * from UserNew where u_name = @uname", con);
cmd.Parameters.Add(new SqlParameter("@uname", uname));

// get data stream
reader = cmd.ExecuteReader();
while(reader.Read())
{
if (reader["u_pass"].ToString() == upass)         
 {return true;}
}

//Password does not match or the username cannot be found
return false;

This will return the exact match and you can then check if the password has been entered correctly.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.