Solved

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

Posted on 2011-09-02
4
378 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
  • 3
4 Comments
 
LVL 14

Accepted Solution

by:
binaryevo earned 500 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
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…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

809 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