0

I am using visual studios 2010, and I have added a database and connected to it with SQLdatasource. I'm creating a basic login. I want the user to enter the login, and when he tries to login, I want to interate through the database and check if the login name exists. How would I select just one column from the database and iterate through it.

I guess the select SQL statement will be

SELECT userName from tblUser

where username is column and tblUser is the table

user1005253
  • 404
  • 2
  • 7
  • 21

1 Answers1

1

You got the SQL statement right, at the end your SQLDataSource will look something like this:

<asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          DataSourceMode="DataReader"
          ConnectionString="Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;"
          SelectCommand="SELECT userName from tblUser">
      </asp:SqlDataSource>

Note: You may want to use a connection string located in your config file:

 ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"

Also, you could also try to execute this query without using a SQLDataSource since it sounds like you will not be binding the result to a control. For example:

using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            "SELECT userName from tblUser", connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
               // check if reader[0] has the name you are looking for

            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }
Ulises
  • 13,229
  • 5
  • 34
  • 50
  • Many thanks. How would I do this with SQLDatasource? We have the select statement, how would you use that Select statement to iterate through the database? – user1005253 Apr 26 '12 at 02:01
  • execute the Select method of the SQLDatasource control and iterate over the dataview object returned. See this page for more details: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.select.aspx – Ulises Apr 26 '12 at 02:03
  • Cheers. Something like this? `DataView dv = (DataView)SqlDataSource3.Select(DataSourceSelectArguments.Empty); while ((dv != null) && (dv.Count > 0)) { DataRow dvUserInfo = dv.Table.Rows[0]; login_txtb.Text.CompareTo(dvUserInfo["userName"].ToString()); }` – user1005253 Apr 26 '12 at 02:18
  • I'm not sure why, but when I run it and click the button which executes this code, nothing happens. The browser just keep trying to load. – user1005253 Apr 26 '12 at 02:33
  • Put a break point on your page load event and see if the code behind is executing at all. Or maybe your server is taking too long to serve the request. There could be multiple reasons. – Ulises Apr 26 '12 at 02:56