Navigation Menu

How to create login form in VB.Net

Posted by rbueno on Jun 10, 2013 | 108 Comments

Visual Basic 2012 also known as VB 11 or Visual Basic .NET is the latest stable release from Microsoft, which implemented on .NET Framework. In this blog entry, we’re going to teach you on how to create login form in VB.Net using Microsoft Access 2007. The reason I choose Access over SQL Server is that I’m used to this database software since my college days but don’t worry, I will post another one using SQL Server when I have time.

The first step is we’re going to create a database for storing user’s information. Open Microsoft Access and create blank database. Make sure you know where you save the file as this is important on OleDB Connection String later. Create table and name it “tbl_user”. Depending on how you design the table, the 3 most important columns are ID, username and password. I have different approach on designing my user table and you may follow it but not recommended. Add these columns: “first_name”, “last_name”, “middle_name”, “age”, “address”, “user_level”, “username”, “password”

Microsoft Office Access 2007

You must populate after creating the table as many as you can for our testing later. Nest step, open Visual Studio and create New Project for Visual Basic under Templates and select Windows Form Application. Name the application on whatever you want but I recommend letting the software do it.

1.1

After you create new project, Visual Studio will create a new form ready to use. We’re going to design this form and name it frmLogin.

1.2

Design the form same as below. Please take note of these important steps:

1.) Rename the username textbox to txtUsername and password textbox to txtPassword

2.) Rename the login button to btnLogin and cancel button to btnCancel

1.3

Double click on Login button. This will show you the coding window and your mouse focus is in inside btnLogin Click declaration as shown below.

1.4

Next step, we need to make sure that user provide both username and password so we are going to use If Else condition statement and OR comparison operator. Add this line inside btnLogin Private Sub.

 

We are using OR operator as it is must satisfy either one of the condition to be TRUE. So if the user enters either only username or password, error will be shown. The first statement is only a reminder of what this particular line of code is all about. Visual Basic compiler will not include this line when executing.

Notice that MessageBox.Show() has 4 arguments? It’s not required for those four completely but only for the first argument. The 1st argument is important as this will be shown to end user of whatever you have written on it. In this case, we’re going to use “Please complete the required fields..” to indicate the user that those fields are important. 2nd argument(  “Authentication Error” )is the MessageBox caption at the left side of those Minimize, Maximize and Close button at the very top. 3rd argument is the button and last one is the icon( Red X ). See the figure below.

1.5

Next step we will do the connecting to database and execute data comparison inside Else condition. Add this line after the Else statement.

 

Please take note that the ConnectionString may vary from machine to machine. In my case, Jet Pack provider is not compatible in 64 bit machine and I use ACE OLEDB instead. To get your connection string, Follow the steps below:

1.)    Go back to design environment window and click on DataBindings in Properties window. Click F4 in you can’t see the Properties window or add it on VIEW->Properties Window.

2.)    Under DataBindings, click on Text->Add Project Data Source. This will give you Data Source Configuration wizard.

3.)    Choose Database as your Data Source Type and click Next.

4.)    Choose Dataset as your Database Model and then click Next.

5.)    Click on New Connection and you will see Add Connection window.

6.)    On the Data source, click Change and choose Microsoft Access Database File.

7.)    Now we’re going to locate the database that we created a while ago. Click on Browse and locate the database. If you create a secured database, enter your Username and Password to make a successful connection. Since this is just a tutorial, I didn’t show you on how to secure a database. However, if you’re going to develop software for distribution, you must secure your database.

8.)    Now click on Test Connection. If you have succeeded, then we’re good to go to next step.

9.)    Click OK to close the Add Connection wizard and expand the “Connection string that you will save in the application”. Copy the connection string given and paste it on conn.ConnectionString

1.6

 

Next step we are going to use Try and Catch the Exception. Go back to your btnLogin Private Sub and add the code below.

The MessageBox instances are the same as the previous one except we concatenate( ampersand & ) the exception message to let us know the exact error.

Add this code inside Try.

The sql string holds the username and password comparison in SQL Statement format. Astrerisk( * ) means that we are going to fetch every column on tbl_user we’ve created earlier on matched record in WHERE condition output.  In checking the required fields earlier, we use OR comparison operator in which only one conditions must be TRUE in order to satisfy. In here, we’re going to use AND as it will proceed only if both conditions are TRUE. Meaning username and password must be matched or it will fail. The sql will be executed and store in sqlRead variable.

Next step, were going to check if user enter correct username and password in order to proceed. Create another form and name it as frmMain. When user has been authenticated, this frmMain will show and we’re going to hide the frmLogin. Otherwise, we’re going to display error message, clear username and password text box and focus the set the input focus to username text field. Add the code below.

Our full code for btnLogin Private Sub will be like this:

Next step we are going to code the btnCancel. It depends on how you want to do with the Cancel button. Mostly, other people simply exiting the program when clicking on Cancel button but in my case, I’m going to clear username and password field text and focus the key to username. So double click on Cancel button and add the code inside the btnCancel Private Sub. Note the below code is the complete Private Sub.

So how the login form looks like when running? Check the screenshots below.

Login form ready to use.

When user enters wrong username and password combination, warning will be shown.

When user forgets to enter both username and password, error message will be shown.

Hopefully you enjoy my little tutorial. Next, I’m going to use SQL Server instead of Access and will share it in the future.

 

 

108 Comments

  1. Rangga
    July 24, 2013

    nice tutorial and very helpful. This is what i’m looking for..simple and easy to understand. Thank you sir

    • Rishab
      April 24, 2015

      Thank you very much for this tutorial its very helpful to me. 🙂

  2. Fundile
    September 3, 2013

    thank you so much. it worked perfectly:)

    • December 21, 2013

      Very good post. I definitely love this site. Thanks!

    • charlenerey
      December 23, 2013

      It’s an awesome paragraph in faѵor of all the internet people; they will take benefіt from it I
      am sure.

    • December 23, 2013

      These are truly fantastic ideas in concerning blogging.
      You have touched some nice factors here. Any
      way keep up wrinting.

    • March 31, 2014

      I’m very happy to discover this page. I wanted to thank you for your time just
      for this fantastic read!! I definitely enjoyed every part of
      it and I have you saved to fav to check out new
      things on your blog.

  3. ankara web tasarim
    September 12, 2013

    Wonderful article! That is the kind of info that are supposed to be
    shared around the net. Disgrace on Google for now not positioning this post upper!
    Come on over and visit my site . Thanks =)

  4. Jorge
    September 21, 2013

    This is Helpful and functioning, More Thanks!

  5. Jesse
    September 26, 2013

    It keeps saying cannot connect to database,perharps you could correct me where i went wrong

    If password.Text = “” Or username.Text = “” Then
    MessageBox.Show(“Please complete the required fields..”, “Authentication Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    ‘ Both fields was supply
    ‘ Check if user exist in database
    ‘ Connect to DB
    Dim conn As New System.Data.OleDb.OleDbConnection()
    conn.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Crown.accdb”

    Try
    ‘conn.Open()
    ‘MsgBox(“Susscess”)

    Dim sql As String = “SELECT * FROM tbl_PASSWORDS WHERE USERNAME='” & username.Text & “‘ AND PASSWORD = ‘” & password.Text & “‘”
    Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)

    ‘Open Database Connection
    sqlCom.Connection = conn
    conn.Open()

    Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()

    If sqlRead.Read() Then
    Home.Show()
    Me.Hide()

    Else
    ‘ If user enter wrong username and password combination
    ‘ Throw an error message
    MessageBox.Show(“Username and Password do not match..”, “Authentication Failure”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    ‘Clear all fields
    password.Text = “”
    username.Text = “”

    ‘Focus on Username field
    username.Focus()
    End If
    Catch ex As Exception
    MessageBox.Show(“Failed to connect to Database..”, “Database Connection Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)

    End Try

    End If
    End Sub

    • September 29, 2013

      Hi there,

      Please use the Connection Wizard in Vb.net then test the connection if successful.

      Thanks

      • Dolefly
        October 16, 2013

        copy your database file to your root director e.g to Drive C and use this connection instead
        conn.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Crown.accdb”

      • Jim K.
        March 14, 2015

        How do I get the other information out of the database? Such as an email field or if I had a security level field? This was a very simple tutorial. Great Job!!!

    • Burak124
      February 14, 2014

      Dim sql As String = “SELECT * FROM tbl_PASSWORDS WHERE USERNAME=’” &
      dont use _ sign on tbl_passwords. visual basic not understanding

    • August 10, 2015

      Change:
      Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
      To:
      Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, Conn)

  6. ken
    October 11, 2013

    Sir,

    Please help, your codes works but every time i log in it says user and pass do not match.
    im using visual studio 2005 and i make my use and pass on my MS Access plss help.

    • Dolefly
      October 16, 2013

      @Ken Have you populate the database with correct credentials?
      Though am learning too,am ready to share!since sharing is caring!

  7. October 11, 2013

    This is a good stuff… Thank you

  8. padma
    October 12, 2013

    hi…sir
    the problem for me is even if i enter correct userid and password,it shows the messagebox enter the required field

  9. VHAN
    October 15, 2013

    Sir is this applicable @ VS2010?

  10. October 18, 2013

    Thanks in favor of sharing such a nice idea, paragraph is good, thats why i have read it completely

  11. October 18, 2013

    […] • Log In Form • How to create login form in VB.Net […]

  12. Umesh
    October 27, 2013

    Good Example. But I have another problem. My application works on network I want to know if any user is already logged in another computer. I found the solution that when user log in to application, I will save that user’s log in status in database and when he/she log off, status will be updated in database. But what if any computer in the network shuts down accidentally by power off or any other. Please let me the know the solution.

  13. October 28, 2013

    Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
    You obviously know what youre talking about, why waste
    your intelligence on just posting videos to your weblog when you could
    be giving us something informative to read?

  14. November 22, 2013

    huhuhu Failed to connect to Database..?

  15. Zak
    November 25, 2013

    Hi
    My login form doesn’t close even if i write me.close, me.hide etc.
    Please let me know the solution of this thanks

  16. sirajahmed
    November 26, 2013

    Hi,

    Have you finished writing for sql server and vb 2012 ?

  17. sadeeq
    November 26, 2013

    pls how can i create login page with 3 different user and also open different pages.

    like sales person ,admin, sales manager
    thank u.

  18. Mitch
    December 6, 2013

    Can you please do this in ACCESS DATABASE ?

    • December 23, 2013

      Hello Mitch,

      This tutorial is already using Access Database.

  19. flor
    December 11, 2013

    BRAVO!
    it is very helpful..very easy to understand,,thanx a lot for the help..keep helping.. 🙂

  20. Rob
    December 17, 2013

    I keep getting failed to connect to DB, I know this tutorial was connecting to Access, and I’ve changed to SQLclient. I have this same “DIM conn As New SqlConnection” on another form to add to database. So i Know the connection parameters are correct. Any Suggestions from anyone would be greatly appreciated.

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ‘ Check if username or password is empty
    If TextBox2.Text = “” Or TextBox1.Text = “” Then
    MessageBox.Show(“Please complete the required fields..”, “Authentication Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    ‘ Both fields was supply
    ‘ Check if user exist in database
    ‘ Connect to DB
    Dim conn As New SqlClient.SqlConnection
    conn.ConnectionString = “Data Source=;Initial Catalog=;User ID=;Password=”

    Try
    ‘conn.Open()
    ‘MsgBox(“Success”)

    Dim sql As String = “SELECT * WHERE Username'” & TextBox1.Text & “‘ AND Password = ‘” & TextBox2.Text & “‘”
    Dim sqlCom As New SqlCommand

    ‘Open Database Connection
    sqlCom.Connection = conn
    conn.Open()
    Dim sqlRead As SqlClient.SqlDataReader = sqlCom.ExecuteReader

    If sqlRead.Read() Then
    Login_Success.Show()
    Me.Hide()

    Else
    ‘ If user enter wrong username and password combination
    ‘ Throw an error message
    MessageBox.Show(“Username and Password do not match..”, “Authentication Failure”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    ‘Clear all fields
    TextBox2.Text = “”
    TextBox1.Text = “”

    ‘Focus on Username field
    TextBox1.Focus()
    End If

    Catch ex As Exception
    MessageBox.Show(“Failed to connect to Database..”, “Database Connection Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

    End If
    End Sub

    • christian
      February 22, 2015

      hi sir can u plz help me? on how to create a log in in vb.net with the username and password with cancelling thru code? tnx

      • ayaanle xared salaax
        May 10, 2016

        want
        login form code in vb and sql
        passowrd and username read database

    • ayaanle xared salaax
      May 10, 2016

      Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
      ‘ Check if username or password is empty
      If TextBox2.Text = “” Or TextBox1.Text = “” Then
      MessageBox.Show(“Please complete the required fields..”, “Authentication Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
      Else
      ‘ Both fields was supply
      ‘ Check if user exist in database
      ‘ Connect to DB
      Dim conn As New SqlClient.SqlConnection
      conn.ConnectionString = “Data Source=;Initial Catalog=;User ID=;Password=”

      Try
      ‘conn.Open()
      ‘MsgBox(“Success”)

      Dim sql As String = “SELECT * WHERE Username’” & TextBox1.Text & “‘ AND Password = ‘” & TextBox2.Text & “‘”
      Dim sqlCom As New SqlCommand

      ‘Open Database Connection
      sqlCom.Connection = conn
      conn.Open()
      Dim sqlRead As SqlClient.SqlDataReader = sqlCom.ExecuteReader

      If sqlRead.Read() Then
      Login_Success.Show()
      Me.Hide()

      Else
      ‘ If user enter wrong username and password combination
      ‘ Throw an error message
      MessageBox.Show(“Username and Password do not match..”, “Authentication Failure”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

      ‘Clear all fields
      TextBox2.Text = “”
      TextBox1.Text = “”

      ‘Focus on Username field
      TextBox1.Focus()
      End If

      Catch ex As Exception
      MessageBox.Show(“Failed to connect to Database..”, “Database Connection Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
      End Try

      End If
      End Sub

  21. Rob
    December 17, 2013

    Last Post didnt Paste correctly, and no option to edit…Here is my code.

    Thanks!

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    ‘ Check if username or password is empty
    If TextBox2.Text = “” Or TextBox1.Text = “” Then
    MessageBox.Show(“Please complete the required fields..”, “Authentication Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    ‘ Both fields was supply
    ‘ Check if user exist in database
    ‘ Connect to DB
    Dim conn As New SqlClient.SqlConnection
    conn.ConnectionString = “;Initial Catalog= My Database Name;User ID=;Password=”

    Try
    ‘conn.Open()
    ‘MsgBox(“Success”)

    Dim sql As String = “SELECT * WHERE User_Name'” & TextBox1.Text & “‘ AND Password = ‘” & TextBox2.Text & “‘”
    Dim sqlCom As New SqlCommand

    ‘Open Database Connection
    sqlCom.Connection = conn
    conn.Open()
    Dim sqlRead As SqlClient.SqlDataReader = sqlCom.ExecuteReader

    If sqlRead.Read() Then
    Login_Success.Show()
    Me.Hide()

    Else
    ‘ If user enter wrong username and password combination
    ‘ Throw an error message
    MessageBox.Show(“Username and Password do not match..”, “Authentication Failure”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    ‘Clear all fields
    TextBox2.Text = “”
    TextBox1.Text = “”

    ‘Focus on Username field
    TextBox1.Focus()
    End If

    Catch ex As Exception
    MessageBox.Show(“Failed to connect to Database..”, “Database Connection Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

    End If
    End Sub

  22. Adil
    January 14, 2014

    where do i put the database file if i am going to install it in another pc?

    • January 19, 2014

      Hi Adil,
      Usually you want to put the database file in some location as the Application exe or you can supply the absolute path to the database in your application, in example you can put in your C: drive root directory.

  23. January 21, 2014

    Hi Kabayan paano po ba mag gawa ng regster form yung gsto ko sana yung papasok sa database na ginawa mo pero lagi akong error so please gawa ka po ng Regster form tutorial na papasok dun sa ginawa na database if ok lang po Thanks.

    • February 27, 2014

      Imports System.Data.OleDb
      Public Class Membership
      Private Sub Membership_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      txtPassword.UseSystemPasswordChar = True
      txtRePassword.UseSystemPasswordChar = True

      End Sub

      Private Sub btnReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReg.Click
      AccountConn.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\JCH Folder\Programming\VB.Net\DrivingSchoolManagementSystem\Database\tbl_AccountDBase.accdb”
      Dim SqlReg As String

      SqlReg = “INSERT INTO tbl_AccountInfo VALUES(” & txtID.Text & “,'” & txtFirstname.Text & “‘,'” & txtLastname.Text & “‘,'” & txtAddress.Text & “‘,'” & txtContact.Text & “‘,'” _
      & cmbGender.Text & “‘,” & txtAge.Text & “,'” & txtDOB.Text & “‘,'” & cmbMarStatus.Text & “‘,'” & txtEmail.Text & “‘,'” & txtUsername.Text & “‘,'” & txtPassword.Text & “‘)”

      Dim DAAccount As New OleDbDataAdapter(SqlReg, AccountConn)
      AccountConn.Open()
      DAAccount.Fill(DSAccount, “Command Out”)
      MsgBox(“Added Succesfully”)
      AccountConn.Close()

      End Sub
      Private Sub txtID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtID.TextChanged
      txtID.Focus()
      End Sub
      End Class

  24. January 21, 2014

    English Version:

    Hi there my friend how can i make a registration form that insert into the database you make can you show us a tutorial to how insert new password and username etc……. and more

    I’m hoping for your positive reply. thanks you!

  25. javi
    February 28, 2014

    Thank you this was very help full

  26. Thet Paing
    March 17, 2014

    Thanks you,

  27. Seija Fr
    March 20, 2014

    This was good article. I am waiting for corresponding for SQL Server – have you done it yet?

  28. Michael
    March 24, 2014

    thank you for this tutorial, it helped.. ALOT.

  29. George
    March 26, 2014

    Please how do I do this in SQL 2012, especially when it come to connecting to the database. do I use the same code as this

    ‘ Connect to DB
    Dim conn As New System.Data.OleDb.OleDbConnection()
    conn.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\LibraryManagementSystem.accdb”

  30. George
    March 26, 2014

    Thanks a lot for the post but I am doing my project in sql and need help to create the login. thank you once again.

  31. March 26, 2014

    […] • Log In Form • How to create login form in VB.Net […]

  32. David Jordan
    March 30, 2014

    Is there a way to use the User_Level field to open different forms depending on the number that is entered in that field?

  33. Ian
    April 11, 2014

    Hi,
    Dim sql As String = “SELECT * FROM tbl_user WHERE username='” & txtUsername.Text & “‘ AND password = ‘” & txtPassword.Text & “‘”

    this my code. i keep getting cannot find the table user…make sure it exists…in my database i have made a table called user

  34. arnel
    April 12, 2014

    Hi!! sir can you post on how to create a sql database server 2012 and connect it to visual studio 2012 for login?

  35. Hani
    April 16, 2014

    Hi , if I have one database that contain different usernames and passwords
    if user1 want to access he should go to form1
    if user2 want to access he should go to form 2
    if user3 want to access he should go to form 3

    how can I create that ? can u do us same explanation but for different user accessing

  36. Ahmad
    April 19, 2014

    ‘ Check if username or password is empty
    If txtPassword.Text = “” Or txtUsername.Text = “” Then
    MessageBox.Show(“Please complete the required fields..”, “Authentication Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    ‘ Both fields was supply
    ‘ Check if user exist in database
    ‘ Connect to DB
    Dim conn As New System.Data.OleDb.OleDbConnection()
    conn.ConnectionString = “Provider=Microsoft.Jet.OLEDB.4.0” + “Data Source=C:\Users\Ahmad\AppData\Local\Temporary Projects\WindowsApplication1\tbl_user1.mdb”

    Try
    ‘conn.Open()
    MsgBox(“Susscess”)

    Dim sql As String = “SELECT * FROM tbl_user1 WHERE username='” & txtUsername.Text & “‘ AND password = ‘” & txtPassword.Text & “‘”
    Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)
    MsgBox(“Susscess3”)
    ‘Open Database Connection
    sqlCom.Connection = conn
    conn.Open()

    MsgBox(“Susscess 1”)
    Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()

    If sqlRead.Read() Then
    MsgBox(“Susscess2”)
    Form2.Show()
    Me.Hide()

    Else
    ‘ If user enter wrong username and password combination
    ‘ Throw an error message
    MessageBox.Show(“Username and Password do not match..”, “Authentication Failure”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    ‘Clear all fields
    txtPassword.Text = “”
    txtUsername.Text = “”

    ‘Focus on Username field
    txtUsername.Focus()
    End If

    Catch ex As Exception
    MessageBox.Show(“Failed to connect to Database..”, “Database Connection Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

    End If

    I use the same code but I can’t open the connection ( conn.open) even the connection test succeeded

  37. idrskom
    April 20, 2014

    HI, sir.
    first at all thanks a lot to your tutorial, it really helped to done my project.
    Now i would like to ask, how we could give memo :
    WELCOME to USERNAME
    into our main page?

  38. April 22, 2014

    Good day sir Rolly 🙂 Would you mind posting the code .. newbie here want to explore more about visual studio thanks

  39. glody
    April 29, 2014

    how can I make a register form,
    have this at the moment
    Public connstring As String = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=U:\IT\com\Database1.accdb”

    Public conn As OleDb.OleDbConnection
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    conn.ConnectionString = connstring
    If conn.State = ConnectionState.Closed Then
    conn.Open()
    MsgBox(“open”)
    Else
    MsgBox(“closed”)
    End If
    End Sub
    Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
    Try
    Dim sqlquery As String = “INSERT INTO tbl_user (Firstname,Surname,Gender,DOB,Address,Postcode,Username,Password) VALUES (‘” & txtFirstname.Text & “‘,'” & txtSurname.Text & “‘,'” & txtGender.Text & “‘,'” & txtAge.Text & “‘,'” & txtAddress.Text & “‘,'” & txtPostcode.Text & “‘,'” & txtRegisterUsername.Text & “‘,'” & txtRegisterPassword.Text & “‘,’)”
    Dim sqlcommand As New OleDb.OleDbCommand

    With sqlcommand
    .CommandText = sqlquery
    .Connection = conn
    .ExecuteNonQuery()

    End With
    MsgBox(“one record Sussessfully Added..”)
    Catch ex As Exception
    MsgBox(ex.ToString)
    End Try

    End Sub

    it keeps showing this errors
    system.data.oleDb.oleDbException(0x80040E14): Syntax errort INSERT INTO stastement

  40. Kwasi
    May 9, 2014

    Can you please do this in SQL DATABASE

  41. Dman
    May 16, 2014

    frmMainform not declared? this error kept on comming up. how do i fix it?

  42. Rose
    June 13, 2014

    such a GREAT, detailed explanation, a problem keeps on happening while debugging though. I use sql server database and the error message that appears is like follows:
    An OLE DB Provider was not specified in the ConnectionString. An example would be, ‘Provider=SQLOLEDB;’
    I copied the connection string as it is after I had followed the same procedure explained:
    Dim conn As New System.Data.OleDb.OleDbConnection()
    conn.ConnectionString = “Data Source=ROSEMOHAMMED;Initial Catalog=HRMS;User ID=sa”
    can you plzz tell me what is the problem?

    • July 7, 2014

      Rose,

      I can’t tell it because I haven’t try the SQL Server yet. I’t in my bucket list since last year but can’t make it because of my busy schedule. When I have time, I’ll try it and see what I can do in your case.

      Thanks

  43. Atul
    June 25, 2014

    Perfect thanks

  44. Mohamed
    July 5, 2014

    Hello Sir,

    I am getting the error “unrecognized database format” when i try to test my DB connection. What shall i do correct this. I have followed each step in this tutorial, and did some research as well. But still no luck. Hope you could help me on this.

    Thanks

  45. rosette
    July 9, 2014

    good day sir , i just want to ask how to know what is the problem if your database can’t connect to vb.net..

    thanks

  46. Marième
    July 10, 2014

    Hello,

    Can you help me please. When I try to run it I got this error “Failed to connect to database”

  47. August 5, 2014

    Hi i am using visual studio 2005, with access 2002 this is my code….

    Public Class Form4

    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click

    ‘ Check if username or password is empty
    If txtPassword.Text = “” Or txtUsername.Text = “” Then
    MessageBox.Show(“Please complete the required fields..”, “Authentication Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    ‘ Both fields was supply
    ‘ Check if user exist in database
    ‘ Connect to DB
    Dim conn As New System.Data.OleDb.OleDbConnection()
    conn.ConnectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\carral\Desktop\CRMLogin.mdb”

    Try
    ‘conn.Open()
    ‘MsgBox(“Susscess”)

    Dim sql As String = “SELECT * FROM tbl_user WHERE Username='” & txtUsername.Text & “‘ AND Password = ‘” & txtPassword.Text & “‘”
    Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql)

    ‘Open Database Connection
    sqlCom.Connection = conn
    conn.Open()

    Dim sqlRead As System.Data.OleDb.OleDbDataReader = sqlCom.ExecuteReader()

    If sqlRead.Read() Then
    Form1.Show()
    Me.Hide()

    Else
    ‘ If user enter wrong username and password combination
    ‘ Throw an error message
    MessageBox.Show(“Username and Password do not match..”, “Authentication Failure”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

    ‘Clear all fields
    txtPassword.Text = “”
    txtUsername.Text = “”

    ‘Focus on Username field
    txtUsername.Focus()
    End If

    Catch ex As Exception
    MessageBox.Show(“Failed to connect to Database..”, “Database Connection Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

    End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    ‘User clicking on cancel button only clears field
    ‘ and refocus to first field
    txtUsername.Text = “”
    txtPassword.Text = “”
    txtUsername.Focus()
    End Sub
    End Class

    This is failing to connect to the database, any ideas?

  48. Tonet Martinez
    August 28, 2014

    Hello sir I would like to know if you are still working on your next tutorial on how to create login form using SQL Server instead of Access?

  49. sakthivel
    September 3, 2014

    it is very useful.thank you…………………………

  50. Naveen
    October 16, 2014

    Thank you for this tutorial 🙂

  51. Sam
    January 21, 2015

    instead of using:
    btnLogin.text = “”
    btnPassword.text = “”

    just use
    btnLogin.clear()
    btnPassword.clear()

    though the solution worked great, thanks!

  52. sam
    January 21, 2015

    i meant txtusername and txtpassword sorry :/

  53. Israel dave
    February 24, 2015

    Thank you very very very much.

  54. Paul
    March 24, 2015

    sir how to use in select * from STATEMENT with 3 value…

    “SELECT * FROM LogInAccount WHERE Username='” & txtUserName.Text & “‘ AND Password = ‘” & txtPassword.Text & “‘ AND UserType = ‘” & txtUserType.Text & “‘”

    this is my code but when i log in the other accounts, it said username and password doesnt match. only one account i can log in? pls correct me ASAP

    thank you sir

  55. Abhishek
    April 9, 2015

    Thank u so much.As a new learner i needed this type of help.

  56. Agboola Joseph
    April 29, 2015

    Hi, I tried the code and it’s working fine. I created more than one record in the access database and i want to be able to view each user’s record when i login with the user’s details. what I’m saying is that I want each user to have its own separate record, how do i go about it?. and also want to know if there are other things I can add to this login form. Thanks

  57. May 23, 2015

    Thank you sir,
    I’m very new user to visual studio at first i thought it was very difficult me, but you made it very easy for me.
    thanks a lot

  58. Abeey
    June 20, 2015

    t works fine

  59. Edith
    June 22, 2015

    Awesome. Thanks, it was really helpful

  60. obed
    August 18, 2015

    please i have followed all the steps but dont understand where u said i should copy the connection string and paste it on con.connection
    thanks

  61. September 10, 2015

    gud

    can u plssss frward m ur mail id

  62. splendour
    September 11, 2015

    hi rolley…
    I ave done everythin there but it isnt working for me plshelp me out

  63. Ilupeju Akeem
    September 20, 2015

    Nice codes! Thanks for the efforts.

  64. Suy
    October 2, 2015

    can we create new user button?

  65. anonymous
    October 19, 2015

    Hello, I hope this site is still active. How if I want to display username at form based on username login after successfully login? TQ

  66. Xfileammb
    October 29, 2015

    I also got error message “Fail to connect to Database.”

  67. Ijann
    November 2, 2015

    Excellent tutorial. Thanks. ^^

  68. George
    November 19, 2015

    very helpful. thank you sir

  69. Kenny
    November 25, 2015

    how about logging out?

  70. Sha
    January 22, 2016

    Hello,

    I’m getting the error ‘name ‘conn’ is not declared” I just copy these codes. Is there something I can add or should I remove something?

    Appreciate your help

    Thanks!

  71. anne
    January 25, 2016

    the program was good but it always show that my password is mismatch.. please help me with this problem sir rolly..

  72. Induwara yatiwella
    January 30, 2016

    It’s wonderful

  73. Induwara yatiwella
    January 30, 2016

    You are amazing thanks a lot

  74. Rishi Bhushan jha
    February 14, 2016

    when I am trying the same method.
    the database connection error.
    please help me

  75. sarmad
    February 16, 2016

    Hey i m having this eror while loging in
    Failed to connect to database plz guide

  76. Divyesh Rajpura
    February 28, 2016

    I have problem with con.Open()
    It shows me Exception

    System.InvalidOperationException’ occurred in System.Data.dll
    ” The ‘Microsoft.ACE.OLEDB.12.0’ provider is not registered on the local machine.”

    How to resolve this error……..

    You have use Try catch but I want solutiion of this exception…….

  77. Herme
    March 12, 2016

    Very simple and informative. . . thanks a lot. .

  78. piyush
    April 3, 2016

    thank you very much you are the awesome dude

  79. Abowabon
    April 16, 2016

    This is so the best tutorial I have come across. Great Work.

    I will be nice for you to reply on comments

  80. Kingsley Monday
    May 5, 2016

    Thanks, l luv u

  81. Tharuth
    May 9, 2016

    I want to use case sensitive username & password, so how could I change the code Sir?

  82. Edgar
    June 8, 2016

    Failed to connect to database….

    I already used Wizard for help and pressed the test connection button and it actually says the connection worked…

    Please help
    Thanks

  83. Eliud
    June 26, 2016

    very informative, i am a beginner and i have followed successfully

  84. Matthew James
    August 18, 2016

    Thanks A LOT ! You’re a Life Saver !
    Godbless

  85. Maryjoy
    August 26, 2016

    i enter this code yet when i enter the username in a capital letter which is small in database its still login what to do?

  86. Abegail Perez
    September 9, 2016

    It really helps me. Credits to the owner. Thank you so much

  87. Kenneth Cortel
    October 25, 2016

    Rolly, your program was the best… very short but very effective usage of commands. You are amazing. ANG GALING MO…

  88. January 31, 2017

    […] A further explanation of the code above can be found at the following address. How to create login form in VB.NET […]

  89. Brilliant Mbumwae
    February 12, 2017

    I’m so glad to come across this your blog, it’s quiet simple and straightforward. Bravo and cheers.

    However, I’m not sure if it’s my or visual studio version error. The code works perfectly in all it’s codes except that after a successful login, the main form loads and unloads; thus terminating the program.

    Did I miss something here? I hope to hear and seeing from you soon

Leave a comment

Your email address will not be published. Required fields are marked *