How To Load Data From Database Into DataGridView In VB.NET

Here we see how to use ADO.net to connect to a SQL Server database and load the table data into DataGridView.
  • 6131
Download Files:
 

Here we see how to use ADO.net to connect to a SQL Server database and also show load data from database into 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 emp

(

empid varchar(40),

empname varchar(30) 

)

go

insert into employee values(1,'monu')

go

insert into employee values(2,'Hari')

go

select * from emp

OUTPUT

 

output-in-VB.NET.gif
 

Load 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 and one Button control on the form. The form looks like this.


Form1-in-VB.NET.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 com As String = "Select empid, empname from Emp"

        Dim Adpt As New SqlDataAdapter(com, con)

        Dim ds As New DataSet()

        Adpt.Fill(ds, "Emp")

        DataGridView1.DataSource = ds.Tables(0)

    End Sub

End Class

 

Now run the application and click on the Button.


run-form1-in-VB.NET.gif 

Categories

More Articles

© 2013 dotNetheaven. All rights reserved.