Visual Basic 2017 Lesson 36: Browsing and Editing Data

In preceding lessons, you have learned how to connect to a database as well as filling up the table with data in Visual Basic 2017, now you shall learn how to manipulate the data in the database. Manipulating data means adding news records, editing records, deleting records, browsing records and more.

36.1 Browsing Records

In this lesson, we will create command buttons and write relevant codes to allow the user to browse the records forward and backward as well as fast forward to the last record and back to the first record.The first button we need to create is for the user to browse the first record. We can use button’s text << to indicate to the user that it is the button to move to the first record and button’s text >> to move to the last record. Besides we can use button’s text < for moving to previous record and button’s text > for moving to next record.

The code for moving to the first record is:MyRowPosition = 0Me.showRecords()
The code for moving to previous record is:If MyRowPosition > 0 ThenMyRowPosition = MyRowPosition – 1Me.showRecords()End If
The code for moving to next record is:If MyRowPosition < (MyDataTbl.Rows.Count – 1) ThenMyRowPosition = MyRowPosition + 1Me.showRecords()End If

36.2 Editing, Saving, Adding and Deleting Records

You can edit any record by navigating to the record and change the data values. However, you need to save the data after editing them. You need to use the update method of the SqlDataAdapter to save the data. The code is:

If MyDataTbl.Rows.Count <> 0 ThenMyDataTbl.Rows(MyRowPosition)(“ContactName”) = txtName.TextMyDataTbl.Rows(MyRowPosition)(“state”) = txtState.TextMyDatAdp.Update(MyDataTbl)End If
You can also add new record or new row to the table using the following code :Dim MyNewRow As DataRow = MyDataTbl.NewRow()MyDataTbl.Rows.Add(MyNewRow)MyRowPosition = MyDataTbl.Rows.Count – 1Me.showRecords()

The code above will present a new record with blank fields for the user to enter the new data. After entering the data, he or she can then click the Save button to save the data.

Lastly, the user might want to delete the data. The code to delete the data is:

Public Class Form1
Private MyDatAdp As New SqlDataAdapter
Private MyCmdBld As New SqlCommandBuilder
Private MyDataTbl As New DataTable
Private MyCn As New SqlConnection
Private MyRowPosition As Integer = 0