In previous lessons, you have learned how to connect to a database as well as filling up the table with data in Visual Basic 2012, now you shall learn how to manipulate data in the database. Manipulating data means adding news records, editing records, deleting records, browsing records and more.
31.1 Browsing Records
The code for moving to the first record is:
MyRowPosition = 0 Me.showRecords() The code for moving to previous record is: If MyRowPosition > 0 Then MyRowPosition = MyRowPosition - 1 Me.showRecords() End IfThe code for moving to next record is: If MyRowPosition < (MyDataTbl.Rows.Count - 1) Then MyRowPosition = MyRowPosition + 1 Me.showRecords() End If
The code for moving to the last record is:
If MyDataTbl.Rows.Count > 0 Then MyRowPosition = MyDataTbl.Rows.Count - 1 Me.showRecords() End If
31.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 Then MyDataTbl.Rows(MyRowPosition)("ContactName") = txtName.Text MyDataTbl.Rows(MyRowPosition)("state") = txtState.Text MyDatAdp.Update(MyDataTbl) End If
You can also add a 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 - 1 Me.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:
If MyDataTbl.Rows.Count <> 0 Then MyDataTbl.Rows(MyRowPosition).Delete() MyDatAdp.Update(MyDataTbl) MyRowPosition = 0 Me.showRecords() End If
The Visual Basic 2012 database program interface is shown below:
Finally, you have learned how to create a database application in Visual Basic 2012. Please try to create your very own database applications in Visual Basic 2012 from now on.