ADO.NET DataAdapter in VB.NET

Here we see how to use ado.net to connect to a database, retrieve records, place them into a dataset using dataadapter and display the records on the web form.
  • 4213
 
Data adapter object

DataAdapter provides the communication between the Dataset and the Datasource. The DataAdapter object is used to retrieve the data from the database and place that data into a DataSet. The DataSet was them bound to a control such as GridView and displayed in a web form.

Creating a SqlDataAdapter Object

To create a SqldataAdapter we call connection object .

Dim adapt As SqlDataAdapter = New SqlDataAdapter(com)

Now creating a table in Database and insert the value. like this

create table emp3

(

firstname varchar(20),

lastname varchar(30)

)

Now using select statement.

select * from emp3

OUTPUT


tt1.gif

Table1.gif

For example

The below example will show the employee firstname and last name from the table emp3 from MS SQL server database on the form. Now taking a Button control and GridView control on the form. The form looks like this.


tt2.gif 

GridView1.gif

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

Imports System.Data.SqlClient

Public Class WebForm1

       Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As 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 New SqlCommand("select * from emp3", con)

        Dim adapt As SqlDataAdapter = New SqlDataAdapter(com)

        Dim dt As New DataSet()

        con.Open()

        adapt.Fill(dt, "emp3")

        con.Close()

        GridView1.DataSource = dt

        GridView1.DataBind()

    End Sub

End Class

Now run the application and click on the button. It shows the database table on the GridView.


tt3.gif

GridView2.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.