简体   繁体   中英

Validating with SQLdatasource - C#

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM