Find specific record from database table in VB.NET

This article describes how to use ADO.net to connect to a SQL Server database, find a specific record from the database table and also display result in DataGridView.
  • 11352
Download Files:
 

This article describes how to use ADO.net to connect to a SQL Server database, find a specific record from the database table and also display result in DataGridView.

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.
 

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


tabl1.gif

Table1.gif
 

Using select statement with like condition

 

To find the specific record from the database table using select statement with like condition.
 

Dim cmd As New SqlCommand("select * from logn where username like '%" + TextBox1.Text + "%'", con)

 

Load the find data from database into DataGridView

 

To load data from database to DataGridView use DataSource property. The DataSource property is used for displaying data.

 

DataGridView1.DataSource = ds.Tables(0)

For example
 

Drag and Drop one DataGridView control, one Button control and one textbox control on the form. The form looks like this.
 

dg1.gif

Figure1.gif
 

Now double click on the Button control and add the following vb.net 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)

        Dim cmd As New SqlCommand("select * from logn where username like '%" + TextBox1.Text + "%'", con)

        Dim Adpt As New SqlDataAdapter(cmd)

        Dim ds As New DataSet()

        If (Adpt.Fill(ds, "logn")) Then

            DataGridView1.DataSource = ds.Tables(0)

            MessageBox.Show("match found")

        Else

            MessageBox.Show("match not found")

        End If

    End Sub

End Class
 

Now run the application and enter text in TextBox control and click on the Button.
 

dg2.gif

Figure2.gif
 

Now we enter the text in textbox which is not in database table.


dg3.gif

Figure3.gif

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.