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();
        }

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.