user1005253
user1005253

Reputation: 404

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

Upvotes: 0

Views: 519

Answers (1)

Ulises
Ulises

Reputation: 13419

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

Upvotes: 1

Related Questions