Monday, May 17, 2010

How to connect, retrieve data from SQL server using VB.net?


"




SqlDataAdapter provides the communication between the Dataset and the Data Source with the help of SqlConnection Object . The SqlConnection Object has no information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Sourcewhere the data coming from. So the SqlDataAdapter manage the communication between these two Objects. The TableMapping Collections help the SqlDataAdapter to do this task.
The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the database with the data modifications that are run on a DataSetobject. The following source code demonstrate how to update a Dataset through SqlDataAdapter using a DataGridView. For running this source code , open a new VB.NET project and drag two buttons and a DataGridView in the default form1 and copy and paste the following Source Code.

Imports System.Data.SqlClient
Public Class Form1
    Dim connetionString As String
    Dim connection As SqlConnection
    Dim adapter As SqlDataAdapter
    Dim cmdBuilder As SqlCommandBuilder
    Dim ds As New DataSet
    Dim changes As DataSet
    Dim sql As String
    Dim i As Int32

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
        connection = New SqlConnection(connetionString)
        Sql = "select * from Product"
        Try
            connection.Open()
            adapter = New SqlDataAdapter(Sql, connection)
            adapter.Fill(ds)
            connection.Close()
            DataGridView1.Data Source= ds.Tables(0)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Try
            cmdBuilder = New SqlCommandBuilder(adapter)
            changes = ds.GetChanges()
            If changes IsNot Nothing Then
                adapter.Update(changes)
            End If
            MsgBox("Changes Done")
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class

see source webpage
  

No comments:

Post a Comment