Match Value From Database User Control in VB.NET

Here we see how to use ado.net to connect to a database and match the value from the database to the user control.
  • 6755
Download Files:
 

Here we see how to use ado.net to connect to a database and match the value from the database to the user control. To do that we make a table in the database and creating connection with database. After the connection using select command to match the value from the database to the user control.

Creating connection object

To create a connection we pass the connection string as a parameter in connection object.

Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

Dim con As New SqlConnection(str)

 

The above string defines the connection string which is used to connect the database with the application.

 

Select command

 

This statement is used to select the rows of data in a table. 

 

Dim com As String = "Select username from logn where username='" & txtuser.Text & "' and  password ='" & txtpass.Text & "';"

Dim cm As New SqlCommand(com, con)

 

Now we create a database table and insert some values in this table. Table looks like this.

 

create table logn

(

username varchar(50),

password varchar(40)

)

go

insert into logn values('monu','mohan')

go

insert into logn values('Rohatash','rohit')

go

insert into logn values('Manoj','singh')

go

select * from logn;

The table looks like this.

 

OUTPUT


output-in-vb.net.gif

 

For example

 

Drag and drop two TextBox and two level control and one Button control on the form. The form looks like this.
 

login-in-vb.net.gif
 

Now double click on the Button control and add the following code.

 

Imports System.Data.SqlClient

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

        Dim con As New SqlConnection(str)

        con.Open()

        Dim com As String = "Select username from logn where username='" & txtuser.Text & "' and  password ='" & txtpass.Text & "';"

        Dim cm As New SqlCommand(com, con)

        Dim rd As SqlDataReader = cm.ExecuteReader()

        If rd.Read() = True Then

            MessageBox.Show("Valid username and password")

        Else

            MessageBox.Show("Invalid username and password", caption:="login")

            txtuser.Clear()

            txtpass.Clear()

        End If

    End Sub

End Class

 

Now run the application and enter the username and password in the TextBox control.
 

enter-username-or-password-in-vb.net-login-window.gif

 

Now click on the Button control.
 

login2-in-vb.net.gif

 

Now enter the correct username and password which match with the database.
 

new-enter-username-or-password-in-vb.net-login-window.gif
 

Now click on the Button control.

 

login3-in-vb.net.gif

Categories

More Articles

© 2018 DotNetHeaven. All rights reserved.