?
Solved

Check if user exist in access database with SqlDataSource. Need someone to check code!

Posted on 2011-09-02
4
Medium Priority
?
385 Views
Last Modified: 2013-11-05
Hello,
I'm learning how to check if user exist. I have write below codes:

SqlDataSource is dedicated to GridView1 as data source.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        SqlDataSource1.SelectCommand = "SELECT COUNT(*) AS Result, username, password " & _
                                      " FROM Tabela1 " & _
                                      " GROUP BY username, password " & _
                                      " HAVING (COUNT(*) = 1) " & _
                                      " AND username = '" & TextBox1.Text & "'" & _
                                      " And password = '" & TextBox2.Text & "'"
        SqlDataSource1.DataBind()

        If GridView1.Rows.Count < 1 Then
            Label1.Text = "user not found it"
        Else
            Label1.Text = "user found it"
        End If


    End Sub

Open in new window


But funny thing is when I type wrong username, or password the code is ok, and get statement "user not found it", and also gridview does not show, as no results come out from Sql . But, after I write correct username, and password, gridview show results, but label1 has still text as "user not found it ". Then I click button again, then label has correct text "user found it".
So, basic problem is not in code it self. But that I need to click 2x button to get right result as end user.
I have add it attachment of my project, if someone would like to check it directly.

Thank you in advancee for help.
Login-if-exist-user-in-database.zip
0
Comment
Question by:dejandejanovic
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 14

Accepted Solution

by:
binaryevo earned 2000 total points
ID: 36475757
First and foremost i would suggest NOT using SQLDataSource and rather abstracting your code out a little bit so that it's more scalable.  I would create a method called Login and exectue a stored procedure on the backend.  The method could look something like this:
public static void Login(string userName, string password)
        {
            _isValid = false;

            try
            {
                using (SqlConnection connection = new SqlConnection(ConnectionString))
                {
                    SqlCommand command = new SqlCommand("TestStoredProcedure", connection);
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@Username", userName);
                    command.Parameters.AddWithValue("@Password", password);

                    if (connection.State == ConnectionState.Open) { connection.Close(); connection.Open(); } else { connection.Open(); }

                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.HasRows)
                    { 
                        while (reader.Read())
                        {
                            UserID = CleanInteger(reader["UserID"]);
                            PrivilegeLevel = CleanInteger(reader["PriveledgeLevel"]);
                        }

                        IsValid = true;
                        reader.Close();
                        if (connection.State == ConnectionState.Open) { connection.Close(); }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Open in new window

0
 

Author Comment

by:dejandejanovic
ID: 36475928
Uf, this is diffucult form. First of all, I'not learning C#, second I'm a begginer, and maybe your example is to hard for me to unerstand it.
0
 

Author Comment

by:dejandejanovic
ID: 36476104
But in the end you have make me start thinking about your code, as C# is not so different as Vb.net.
So, here is my new project. And, it works :-) !
Imports System.Data.OleDb
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Login_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login.Click
        Dim connect As String = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=C:\Documents and Settings\DEJANC\Desktop\WebSite1\test.accdb"
        Dim query As String
        query = "Select Count(*) From Tabela1 Where Username = ? And Password = ?"
        Dim result As Integer = 0
        Using conn As New OleDbConnection(connect)
            Using cmd As New OleDbCommand(query, conn)
                cmd.Parameters.AddWithValue("", UserName.Text)
                cmd.Parameters.AddWithValue("", Password.Text)
                conn.Open()
                Session("Username") = UserName.Text
                result = DirectCast(cmd.ExecuteScalar(), Integer)
            End Using
        End Using
        If result > 0 Then
            Literal1.Text = "OK"
        Else
            Literal1.Text = "NOT OK"
        End If


    End Sub
End Class

Open in new window

0
 

Author Closing Comment

by:dejandejanovic
ID: 36476107
Thank you!
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question