1 Previous Next 

SQL Server: Simple sample of update while row changed


This sample is not meant to use it completetly. However it shows how to handle the eventhandler to avoid raising the change event and it shows how to use a commandbuilder. It needs only a form with on that a datagridview and a button

Imports System.Data.SqlClient

Imports System.Data

Public Class Form1

    Private da As SqlDataAdapter

    Private dt As New DataTable

    Private Sub Form1_Load(ByVal sender As System.Object, _

    ByVal e As System.EventArgsHandles MyBase.Load

        Using conn As New SqlConnection("Server=(Local);" & _

                      "DataBase=Northwind; Integrated Security=SSPI")

            Dim sqlstr As String = "SELECT * FROM Employees"

            Using da = New SqlDataAdapter(sqlstr, conn)

                da.Fill(dt)

            End Using

            DataGridView1.DataSource = dt

            AddHandler dt.RowChanged, AddressOf dt_RowChanged

        End Using

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _

    ByVal e As System.EventArgsHandles Button1.Click

        If dt.Rows(2)("FirstName").ToString = "Janet" Then

            dt.Rows(2)("FirstName") = "Marie"

        Else

            dt.Rows(2)("FirstName") = "Janet"

        End If

    End Sub

    Private Sub dt_RowChanged(ByVal sender As Object, _

    ByVal e As System.Data.DataRowChangeEventArgs)

        Dim cmb As New SqlCommandBuilder(da)

        da.Update(dt)

    End Sub

End Class




1 Previous Next