Lesson 36: Editing Data in Database
Learn how to update, delete, and manage database records in VB2022 applications
Key Takeaway
Mastering CRUD operations (Create, Read, Update, Delete) is essential for building dynamic database applications in VB2022.
Building on the database connection skills from Lesson 35, we'll now explore how to edit, update, and manage database records in VB2022. These skills are essential for creating fully functional database applications.
36.1 CRUD Operations Overview
CRUD operations form the foundation of database interactions:
Create
Adding new records to the database
Read
Retrieving and displaying records
Update
Modifying existing records
Delete
Removing records from the database
36.2 Navigating Records
Implement navigation controls to browse through database records:
Private currentPosition As Integer = 0 Private dt As New DataTable ' Move to first record Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click currentPosition = 0 ShowCurrentRecord() End Sub ' Move to previous record Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click If currentPosition > 0 Then currentPosition -= 1 ShowCurrentRecord() End If End Sub ' Move to next record Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click If currentPosition < dt.Rows.Count - 1 Then currentPosition += 1 ShowCurrentRecord() End If End Sub ' Move to last record Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click If dt.Rows.Count > 0 Then currentPosition = dt.Rows.Count - 1 ShowCurrentRecord() End If End Sub ' Display current record Private Sub ShowCurrentRecord() If dt.Rows.Count = 0 Then Return txtName.Text = dt.Rows(currentPosition)("ContactName").ToString() txtState.Text = dt.Rows(currentPosition)("State").ToString() lblPosition.Text = $"Record {currentPosition + 1} of {dt.Rows.Count}" End Sub
36.3 Updating Records
Modify existing records and save changes to the database:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click ' Validate input If String.IsNullOrWhiteSpace(txtName.Text) Then MessageBox.Show("Contact name is required", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning) Return End If Try ' Update DataTable dt.Rows(currentPosition)("ContactName") = txtName.Text dt.Rows(currentPosition)("State") = txtState.Text ' Update database Dim adapter As New SqlDataAdapter() Dim cmdBuilder As New SqlCommandBuilder(adapter) adapter.Update(dt) MessageBox.Show("Record updated successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information) Catch ex As Exception MessageBox.Show("Error updating record: " & ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub

Figure 36.1: Database Editor Interface
36.4 Adding New Records
Create functionality to add new records to the database:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click ' Create a new row Dim newRow As DataRow = dt.NewRow() ' Set default values newRow("ContactName") = "[New Contact]" newRow("State") = "" ' Add to DataTable dt.Rows.Add(newRow) ' Move to new record currentPosition = dt.Rows.Count - 1 ShowCurrentRecord() ' Focus on name field for editing txtName.Focus() txtName.SelectAll() End Sub
36.5 Deleting Records
Implement safe deletion with user confirmation:
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click If dt.Rows.Count = 0 Then Return ' Get contact name for confirmation Dim contactName As String = dt.Rows(currentPosition)("ContactName").ToString() ' Confirm deletion Dim result As DialogResult = MessageBox.Show( $"Are you sure you want to delete '{contactName}'?", "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) If result = DialogResult.Yes Then Try ' Delete from DataTable dt.Rows(currentPosition).Delete() ' Update database Dim adapter As New SqlDataAdapter() Dim cmdBuilder As New SqlCommandBuilder(adapter) adapter.Update(dt) ' Refresh data and position dt.AcceptChanges() If currentPosition > dt.Rows.Count - 1 Then currentPosition = dt.Rows.Count - 1 End If ShowCurrentRecord() MessageBox.Show("Record deleted successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information) Catch ex As Exception MessageBox.Show("Error deleting record: " & ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End If End Sub
36.6 Complete Implementation
Here's the complete code for a database editor application:
Imports System.Data.SqlClient Public Class DatabaseEditor Private connectionString As String = "Server=localhost\SQLEXPRESS;Database=ContactsDB;Integrated Security=True;" Private dt As New DataTable() Private currentPosition As Integer = 0 Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load LoadData() ShowCurrentRecord() End Sub Private Sub LoadData() Try Using conn As New SqlConnection(connectionString) conn.Open() Dim query As String = "SELECT * FROM Contacts" Dim adapter As New SqlDataAdapter(query, conn) dt.Clear() adapter.Fill(dt) End Using Catch ex As Exception MessageBox.Show("Error loading data: " & ex.Message, "Database Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End Sub ' ... Navigation methods from earlier ... ' ... Update, Add, Delete methods from earlier ... End Class
Database Editing Summary
Master these essential concepts for database editing in VB2022:
Operation | Key Component | Best Practices |
---|---|---|
Navigation | Position tracking | Boundary checks |
Updating | DataAdapter.Update() | Input validation, error handling |
Adding | DataTable.NewRow() | Set default values, focus UI |
Deleting | DataRow.Delete() | Confirmation dialog |
Data Integrity
Always validate user input before saving to the database to maintain data quality and consistency.
User Experience
Provide clear feedback for all operations (success messages, error notifications).
Error Handling
Use try-catch blocks around all database operations to handle potential errors gracefully.
Practical Exercises
Apply your database editing knowledge with these hands-on exercises:
Exercise 1: Contact Manager
Create a contact management application with full CRUD functionality and search capabilities.
Exercise 2: Record Counter
Add a status display showing the current record position and total records (e.g., "Record 3 of 15").
Exercise 3: Undo Functionality
Implement an "Undo" button that reverts changes made to the current record before saving.
Exercise 4: Data Validation
Enhance validation to check for duplicate email addresses and proper email formatting.
Exercise 5: Audit Trail
Create an audit system that logs all changes (add, edit, delete) to a separate database table.
Challenge Exercise: Product Inventory
Develop a complete inventory management system with categories, products, stock tracking, and reporting.
Next Lesson
Learn how to build console applications in Lesson 37: Console Applications Part 1.
Related Resources

Visual Basic 2022 Made Easy
The ultimate beginner-friendly guide for mastering Windows-based application development using Visual Basic in Visual Studio 2022. Whether you're a student, teacher, hobbyist, or self-learner, this book offers a clear, step-by-step approach to help you get started with ease.
What You'll Learn:
- Control structures and procedures
- Decision-making techniques
- Efficient code organization
- Practical application development
- Best practices in VB2022

Mastering Excel VBA 365
Your ultimate step-by-step guide to automating tasks, building macros, and creating powerful applications within Microsoft Excel 365. Whether you're a student, business professional, or aspiring programmer, this comprehensive handbook will help you unlock the full potential of Excel's VBA.
What You'll Learn:
- Control structures in VBA
- Decision-making techniques
- Data processing and analysis
- Report generation
- Automated workflows