Solved

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

Posted on 2011-09-02
4
372 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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

758 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now