'Create a new table in Sql Expresss 2005 and call it Employees2 (in case
'Employees already exists). Create three columns FirstName, LastName
'and EmployeeID (autoIncrement as primary key).
'Drop onto the form a btnLoad, btnUpdate, and a DatagridView.
-then replace all the code in the editor with this code.
Imports System.Data.SqlClient
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.EventArgs) Handles MyBase.Load
AddHandler btnUpdate.Click, AddressOf btnUpdate_Click
AddHandler btnLoad.Click, AddressOf btnLoad_Click
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
da.Update(dt)
btnLoad.PerformClick()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
dt.Rows.Clear()
dt = New DataTable
Dim connectionString As String = "Server=.\SQLExpress; Trusted_Connection=Yes; Database=Employees;"
da = New SQLDataAdapter("SELECT FirstName, LastName, EmployeeID FROM Employees2", connectionString)
Try
dt.BeginLoadData() 'increase performance
da.Fill(dt)
dt.EndLoadData() '
Catch ex As Exception
MsgBox("Error was: " + ex.Message)
da.Dispose()
Return
End Try
Dim bs As New BindingSource
bs.DataSource = dt
DataGridView1.DataSource = bs
DataGridView1.Columns("EmployeeID").ReadOnly = True
'This code this allows the user to INSERT rows, UPDATE rows, and DELETE rows.
Dim cn As SQLConnection = da.SelectCommand.Connection
da.UpdateCommand = New SQLCommand()
da.UpdateCommand.Connection = cn
da.UpdateCommand.CommandText = _
"UPDATE Employees2 SET Firstname = @FirstName, LastName = @LastName WHERE EmployeeID = @EmployeeID"
da.UpdateCommand.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50, "Firstname")
da.UpdateCommand.Parameters.Add("@LastName", SqlDbType.NVarChar, 50, "LastName")
da.UpdateCommand.Parameters.Add("@EmployeeID", SqlDbType.BigInt, 8, "EmployeeID")
da.DeleteCommand = New SQLCommand
da.DeleteCommand.Connection = cn
da.DeleteCommand.CommandText = "Delete From Employees2 Where EmployeeID = @EmployeeID"
da.DeleteCommand.Parameters.Add("@EmployeeID", SqlDbType.BigInt, 5, "EmployeeID")
da.InsertCommand = New SQLCommand
da.InsertCommand.Connection = cn
da.InsertCommand.CommandText = "Insert Into Employees2" _
& "(LastName, Firstname)" & "Values (@LastName, @FirstName)"
da.InsertCommand.Parameters.Add("@Lastname", SqlDbType.NVarChar, 50, "LastName")
da.InsertCommand.Parameters.Add("@Firstname", SqlDbType.NVarChar, 50, "FirstName")
End Sub
End Class