Sure, let's create the Visual Basic code and the MS Access Database structure for the Library
Management System.
Important Notes Before You Start:
1. Software Required:
○ Microsoft Access: To create the database file (.accdb).
○ Microsoft Visual Studio (or Visual Basic Express): To develop the Visual Basic
application. For O-Level, a free version like Visual Studio Community Edition or an
older Visual Basic Express might be suitable.
2. Project Setup in Visual Basic:
○ Open Visual Studio.
○ Create a new project: Choose "Windows Forms App (.NET Framework)" (or
"Windows Forms Application" depending on your VS version).
○ Name your project (e.g., LibraryManagementSystemVB).
3. Database File Location:
○ Save your MS Access database file (LibraryDB.accdb) in the same folder as your
Visual Basic project's executable (.exe) file (usually in the bin\Debug folder within
your project directory). This makes connecting easier with a relative path.
Alternatively, you can use an absolute path, but relative paths are often preferred
for portability.
4. Connecting to Access (ADO.NET):
○ We'll use ADO.NET with the OleDb provider to connect to Access.
○ You'll need to add Imports System.Data.OleDb at the top of your VB code files.
Part 1: MS Access Database Setup
First, let's create the database structure in Microsoft Access.
Database Name: LibraryDB.accdb
Tables to Create:
1. tblBooks
This table will store details about each book in the library.
Field Name Data Type Description Primary Key
BookID AutoNumber Unique identifier for Yes
each book
Title Short Text Title of the book
Author Short Text Author(s) of the book
ISBN Short Text International Standard (Index, No Duplicates)
Book Number
Genre Short Text Category/Genre of the
book
TotalCopies Number (Long Integer) Total number of copies
owned
AvailableCopies Number (Long Integer) Number of copies
currently available
Steps to create tblBooks in Access:
1. Open MS Access.
2. Create a new Blank Desktop Database. Name it LibraryDB.
3. In the "Create" tab, click "Table Design".
4. Add the fields as listed above, setting their Data Types.
5. Set BookID as the Primary Key.
6. For ISBN, in Field Properties, set "Indexed" to "Yes (No Duplicates)".
7. Save the table as tblBooks.
2. tblBorrowers
This table will store details about library users (students/staff).
Field Name Data Type Description Primary Key
BorrowerID AutoNumber Unique identifier for Yes
each borrower
StudentName Short Text Full Name of the
student/borrower
Form Short Text Student's current
form/grade
ContactNumber Short Text Borrower's phone
number
EmailAddress Short Text Borrower's email
address (optional)
Steps to create tblBorrowers in Access:
1. In the "Create" tab, click "Table Design".
2. Add the fields as listed above, setting their Data Types.
3. Set BorrowerID as the Primary Key.
4. Save the table as tblBorrowers.
3. tblBorrowingRecords
This table will log each borrowing and returning transaction.
Field Name Data Type Description Primary Key
RecordID AutoNumber Unique ID for each Yes
transaction
BookID_FK Number (Long Integer) Foreign Key linking to
tblBooks
BorrowerID_FK Number (Long Integer) Foreign Key linking to
tblBorrowers
BorrowDate Date/Time Date the book was
borrowed
DueDate Date/Time Date the book is due
for return
ReturnDate Date/Time Date the book was
actually returned (can
be blank if not returned)
Steps to create tblBorrowingRecords in Access:
1. In the "Create" tab, click "Table Design".
2. Add the fields as listed above, setting their Data Types.
3. Set RecordID as the Primary Key.
4. Save the table as tblBorrowingRecords.
Relationships:
After creating all three tables, you need to establish relationships between them to ensure data
integrity.
Steps to create Relationships in Access:
1. Go to "Database Tools" tab.
2. Click "Relationships".
3. Add all three tables (tblBooks, tblBorrowers, tblBorrowingRecords) to the Relationships
window.
4. Create Relationship 1:
○ Drag BookID from tblBooks to BookID_FK in tblBorrowingRecords.
○ In the "Edit Relationships" dialog box, check "Enforce Referential Integrity".
○ Click "Create".
5. Create Relationship 2:
○ Drag BorrowerID from tblBorrowers to BorrowerID_FK in tblBorrowingRecords.
○ In the "Edit Relationships" dialog box, check "Enforce Referential Integrity".
○ Click "Create".
6. Save the relationships.
Your database is now ready! Remember to save it as LibraryDB.accdb.
Part 2: Visual Basic (Windows Forms Application) Code
We'll create a simple MDI (Multiple Document Interface) parent form and separate child forms
for each management module (Book Catalog, Borrower Registration, Borrow/Return).
Visual Basic Project Setup:
1. Start a new "Windows Forms App (.NET Framework)" project in Visual Studio.
Name it LibraryManagementSystemVB.
2. Add Reference:
○ In Solution Explorer, right-click on your project name -> "Add" -> "Reference...".
○ In the "Reference Manager" dialog, go to "Assemblies" -> "Framework".
○ Search for and select System.Data.OleDb. Click "OK".
3. Add Imports System.Data.OleDb to the top of all code files where you interact with
the database.
A. Module1.vb (For Global Connection String)
This module will hold our database connection string, making it easy to change if needed.
Imports System.Data.OleDb
Module Module1
' Connection string for MS Access database
' Adjust the Data Source path if your database file is in a
different location.
' It's recommended to place LibraryDB.accdb in your VB project's
bin\Debug folder for easy relative path.
Public ConString As String =
"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=|DataDirectory|\LibraryDB.accdb;"
' You can also try: Public ConString As String =
"Provider=Microsoft.ACE.OLEDB.16.0;Data
Source=|DataDirectory|\LibraryDB.accdb;"
' if you are using a newer version of Office/Access.
' Or use a full path: Public ConString As String =
"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:\YourProjectFolder\bin\Debug\LibraryDB.accdb;"
Public Con As OleDbConnection
Public da As OleDbDataAdapter
Public dt As DataTable
Public cmd As OleDbCommand
' Function to open the database connection
Public Sub OpenConnection()
If Con Is Nothing Then
Con = New OleDbConnection(ConString)
End If
If Con.State = ConnectionState.Closed Then
Con.Open()
End If
End Sub
' Function to close the database connection
Public Sub CloseConnection()
If Con IsNot Nothing AndAlso Con.State = ConnectionState.Open
Then
Con.Close()
End If
End Sub
End Module
B. frmMainMDI.vb (MDI Parent Form)
This will be your main application window.
1. Change Form1 to frmMainMDI:
○ In Solution Explorer, right-click Form1.vb -> "Rename" -> frmMainMDI.vb.
○ Double-click frmMainMDI.vb to open its design view.
○ In the Properties window for frmMainMDI, set IsMdiContainer to True.
○ Set WindowState to Maximized.
○ Set Text to "Kuwadzana 1 High School Library Management System".
2. Add a MenuStrip control:
○ Drag a MenuStrip from the Toolbox onto frmMainMDI.
○ Configure it with the following top-level items:
■ &Management
■ &Books (Name: mnuBooks)
■ &Borrowers (Name: mnuBorrowers)
■ - (Separator)
■ &Exit (Name: mnuExit)
■ &Transactions
■ &Borrow / Return Books (Name: mnuBorrowReturn)
■ &Reports
■ &View All Books (Name: mnuViewAllBooks)
■ &Borrowed Books (Name: mnuBorrowedBooks)
■ &Overdue Books (Name: mnuOverdueBooks)
■ &Window (Auto-generated by MDI)
■ &Help
3. Code for frmMainMDI.vb:
Imports System.Data.OleDb
Public Class frmMainMDI
Private Sub frmMainMDI_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
' Ensure the connection can be opened when the main form loads
Try
OpenConnection()
CloseConnection() ' Close immediately after testing
connection
Me.Text = "Kuwadzana 1 High School Library Management
System - Connected"
Catch ex As Exception
MessageBox.Show("Error connecting to database: " &
ex.Message & vbCrLf & _
"Please ensure 'LibraryDB.accdb' is in the
application's 'bin\Debug' folder.", _
"Database Connection Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Text = "Kuwadzana 1 High School Library Management
System - DISCONNECTED"
mnuBooks.Enabled = False
mnuBorrowers.Enabled = False
mnuBorrowReturn.Enabled = False
mnuViewAllBooks.Enabled = False
mnuBorrowedBooks.Enabled = False
mnuOverdueBooks.Enabled = False
End Try
End Sub
Private Sub mnuBooks_Click(sender As Object, e As EventArgs)
Handles mnuBooks.Click
Dim frm As New frmBookCatalog()
frm.MdiParent = Me
frm.Show()
End Sub
Private Sub mnuBorrowers_Click(sender As Object, e As EventArgs)
Handles mnuBorrowers.Click
Dim frm As New frmBorrowerRegistration()
frm.MdiParent = Me
frm.Show()
End Sub
Private Sub mnuBorrowReturn_Click(sender As Object, e As
EventArgs) Handles mnuBorrowReturn.Click
Dim frm As New frmBorrowReturn()
frm.MdiParent = Me
frm.Show()
End Sub
Private Sub mnuViewAllBooks_Click(sender As Object, e As
EventArgs) Handles mnuViewAllBooks.Click
' A simple way to display all books without a dedicated form
for now
Try
OpenConnection()
Dim sql As String = "SELECT * FROM tblBooks"
da = New OleDbDataAdapter(sql, Con)
dt = New DataTable()
da.Fill(dt)
Dim reportForm As New Form()
reportForm.Text = "All Books in Library"
reportForm.MdiParent = Me
reportForm.WindowState = FormWindowState.Maximized
Dim dgv As New DataGridView()
dgv.Dock = DockStyle.Fill
dgv.DataSource = dt
dgv.ReadOnly = True
dgv.AllowUserToAddRows = False
dgv.BackgroundColor = Color.LightSteelBlue ' Set a color
similar to school blue
reportForm.Controls.Add(dgv)
reportForm.Show()
Catch ex As Exception
MessageBox.Show("Error loading all books: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub mnuBorrowedBooks_Click(sender As Object, e As
EventArgs) Handles mnuBorrowedBooks.Click
Try
OpenConnection()
Dim sql As String = "SELECT B.Title, B.Author,
BR.StudentName, TR.BorrowDate, TR.DueDate " & _
"FROM (tblBorrowingRecords AS TR INNER
JOIN tblBooks AS B ON TR.BookID_FK = B.BookID) " & _
"INNER JOIN tblBorrowers AS BR ON
TR.BorrowerID_FK = BR.BorrowerID " & _
"WHERE TR.ReturnDate IS NULL"
da = New OleDbDataAdapter(sql, Con)
dt = New DataTable()
da.Fill(dt)
Dim reportForm As New Form()
reportForm.Text = "Currently Borrowed Books"
reportForm.MdiParent = Me
reportForm.WindowState = FormWindowState.Maximized
Dim dgv As New DataGridView()
dgv.Dock = DockStyle.Fill
dgv.DataSource = dt
dgv.ReadOnly = True
dgv.AllowUserToAddRows = False
dgv.BackgroundColor = Color.LightSteelBlue
reportForm.Controls.Add(dgv)
reportForm.Show()
Catch ex As Exception
MessageBox.Show("Error loading borrowed books: " &
ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub mnuOverdueBooks_Click(sender As Object, e As
EventArgs) Handles mnuOverdueBooks.Click
Try
OpenConnection()
Dim sql As String = "SELECT B.Title, B.Author,
BR.StudentName, TR.BorrowDate, TR.DueDate, " & _
"DateDiff('d', TR.DueDate, Date()) AS
DaysOverdue " & _
"FROM (tblBorrowingRecords AS TR INNER
JOIN tblBooks AS B ON TR.BookID_FK = B.BookID) " & _
"INNER JOIN tblBorrowers AS BR ON
TR.BorrowerID_FK = BR.BorrowerID " & _
"WHERE TR.ReturnDate IS NULL AND
TR.DueDate < Date()"
da = New OleDbDataAdapter(sql, Con)
dt = New DataTable()
da.Fill(dt)
Dim reportForm As New Form()
reportForm.Text = "Overdue Books"
reportForm.MdiParent = Me
reportForm.WindowState = FormWindowState.Maximized
Dim dgv As New DataGridView()
dgv.Dock = DockStyle.Fill
dgv.DataSource = dt
dgv.ReadOnly = True
dgv.AllowUserToAddRows = False
dgv.BackgroundColor = Color.LightCoral ' Highlight overdue
books with a different color
reportForm.Controls.Add(dgv)
If dt.Rows.Count = 0 Then
MessageBox.Show("No books are currently overdue.", "No
Overdue Books", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
reportForm.Show()
Catch ex As Exception
MessageBox.Show("Error loading overdue books: " &
ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub mnuExit_Click(sender As Object, e As EventArgs)
Handles mnuExit.Click
Application.Exit()
End Sub
End Class
C. frmBookCatalog.vb (Book Management Form)
1. Add a new "Windows Form" to your project. Name it frmBookCatalog.vb.
2. Design frmBookCatalog:
○ Labels: Title, Author, ISBN, Genre, Total Copies, Available Copies.
○ Textboxes: txtTitle, txtAuthor, txtISBN, txtGenre, txtTotalCopies, txtAvailableCopies
(make txtAvailableCopies ReadOnly, as it will be calculated).
○ Buttons:
■ btnAdd (Text: "Add Book")
■ btnUpdate (Text: "Update Book")
■ btnDelete (Text: "Delete Book")
■ btnClear (Text: "Clear Fields")
■ btnSearch (Text: "Search")
○ Textbox for Search: txtSearch
○ DataGridView: dgvBooks (for displaying book list).
○ Label: lblBookID (to display the selected BookID, hidden initially).
3. Code for frmBookCatalog.vb:
Imports System.Data.OleDb
Public Class frmBookCatalog
Private Sub frmBookCatalog_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
LoadBooks()
ClearFields()
lblBookID.Visible = False ' Hide BookID label
End Sub
Private Sub LoadBooks(Optional ByVal searchQuery As String = "")
Try
OpenConnection()
Dim sql As String = "SELECT * FROM tblBooks"
If Not String.IsNullOrEmpty(searchQuery) Then
sql &= " WHERE Title LIKE '%" & searchQuery & "%' OR
Author LIKE '%" & searchQuery & "%' OR ISBN LIKE '%" & searchQuery &
"%'"
End If
da = New OleDbDataAdapter(sql, Con)
dt = New DataTable()
da.Fill(dt)
dgvBooks.DataSource = dt
dgvBooks.ReadOnly = True
dgvBooks.AllowUserToAddRows = False
Catch ex As Exception
MessageBox.Show("Error loading books: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub ClearFields()
txtTitle.Clear()
txtAuthor.Clear()
txtISBN.Clear()
txtGenre.Clear()
txtTotalCopies.Clear()
txtAvailableCopies.Clear()
lblBookID.Text = ""
btnAdd.Enabled = True
btnUpdate.Enabled = False
btnDelete.Enabled = False
txtTitle.Focus()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs)
Handles btnClear.Click
ClearFields()
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles
btnAdd.Click
' --- Validation ---
If String.IsNullOrWhiteSpace(txtTitle.Text) OrElse
String.IsNullOrWhiteSpace(txtAuthor.Text) OrElse _
String.IsNullOrWhiteSpace(txtISBN.Text) OrElse
String.IsNullOrWhiteSpace(txtTotalCopies.Text) Then
MessageBox.Show("Please fill in all mandatory fields
(Title, Author, ISBN, Total Copies).", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Dim totalCopies As Integer
If Not Integer.TryParse(txtTotalCopies.Text, totalCopies)
OrElse totalCopies <= 0 Then
MessageBox.Show("Total Copies must be a positive number.",
"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Try
OpenConnection()
Dim sql As String = "INSERT INTO tblBooks (Title, Author,
ISBN, Genre, TotalCopies, AvailableCopies) VALUES (@Title, @Author,
@ISBN, @Genre, @TotalCopies, @AvailableCopies)"
cmd = New OleDbCommand(sql, Con)
cmd.Parameters.AddWithValue("@Title", txtTitle.Text)
cmd.Parameters.AddWithValue("@Author", txtAuthor.Text)
cmd.Parameters.AddWithValue("@ISBN", txtISBN.Text)
cmd.Parameters.AddWithValue("@Genre", txtGenre.Text)
cmd.Parameters.AddWithValue("@TotalCopies", totalCopies)
cmd.Parameters.AddWithValue("@AvailableCopies",
totalCopies) ' Initially available copies = total copies
cmd.ExecuteNonQuery()
MessageBox.Show("Book added successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadBooks()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error adding book: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs)
Handles btnUpdate.Click
If String.IsNullOrWhiteSpace(lblBookID.Text) Then
MessageBox.Show("Please select a book to update.",
"Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
' --- Validation ---
If String.IsNullOrWhiteSpace(txtTitle.Text) OrElse
String.IsNullOrWhiteSpace(txtAuthor.Text) OrElse _
String.IsNullOrWhiteSpace(txtISBN.Text) OrElse
String.IsNullOrWhiteSpace(txtTotalCopies.Text) Then
MessageBox.Show("Please fill in all mandatory fields
(Title, Author, ISBN, Total Copies).", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Dim totalCopies As Integer
If Not Integer.TryParse(txtTotalCopies.Text, totalCopies)
OrElse totalCopies <= 0 Then
MessageBox.Show("Total Copies must be a positive number.",
"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Try
OpenConnection()
' First, get current borrowed count for this book
Dim currentBorrowedCount As Integer = 0
Dim borrowedSql As String = "SELECT COUNT(*) FROM
tblBorrowingRecords WHERE BookID_FK = @BookID AND ReturnDate IS NULL"
cmd = New OleDbCommand(borrowedSql, Con)
cmd.Parameters.AddWithValue("@BookID",
CInt(lblBookID.Text))
Dim result As Object = cmd.ExecuteScalar()
If result IsNot DBNull.Value Then
currentBorrowedCount = CInt(result)
End If
If totalCopies < currentBorrowedCount Then
MessageBox.Show("Total copies cannot be less than the
number of currently borrowed copies (" & currentBorrowedCount & ").",
"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Dim availableCopies As Integer = totalCopies -
currentBorrowedCount
Dim sql As String = "UPDATE tblBooks SET Title = @Title,
Author = @Author, ISBN = @ISBN, Genre = @Genre, TotalCopies =
@TotalCopies, AvailableCopies = @AvailableCopies WHERE BookID =
@BookID"
cmd = New OleDbCommand(sql, Con)
cmd.Parameters.AddWithValue("@Title", txtTitle.Text)
cmd.Parameters.AddWithValue("@Author", txtAuthor.Text)
cmd.Parameters.AddWithValue("@ISBN", txtISBN.Text)
cmd.Parameters.AddWithValue("@Genre", txtGenre.Text)
cmd.Parameters.AddWithValue("@TotalCopies", totalCopies)
cmd.Parameters.AddWithValue("@AvailableCopies",
availableCopies) ' Calculated available copies
cmd.Parameters.AddWithValue("@BookID",
CInt(lblBookID.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("Book updated successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadBooks()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error updating book: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs)
Handles btnDelete.Click
If String.IsNullOrWhiteSpace(lblBookID.Text) Then
MessageBox.Show("Please select a book to delete.",
"Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
If MessageBox.Show("Are you sure you want to delete this book?
All associated borrowing records will be affected.", "Confirm Delete",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No
Then
Return
End If
Try
OpenConnection()
' Optional: Check if the book is currently borrowed before
allowing deletion
Dim borrowedCount As Integer = 0
Dim checkBorrowedSql As String = "SELECT COUNT(*) FROM
tblBorrowingRecords WHERE BookID_FK = @BookID AND ReturnDate IS NULL"
cmd = New OleDbCommand(checkBorrowedSql, Con)
cmd.Parameters.AddWithValue("@BookID",
CInt(lblBookID.Text))
Dim result As Object = cmd.ExecuteScalar()
If result IsNot DBNull.Value Then
borrowedCount = CInt(result)
End If
If borrowedCount > 0 Then
MessageBox.Show("Cannot delete book: " & borrowedCount
& " copies are currently borrowed. Please ensure all copies are
returned.", "Deletion Blocked", MessageBoxButtons.OK,
MessageBoxIcon.Warning)
Return
End If
' Delete associated borrowing records first due to
referential integrity
Dim deleteRecordsSql As String = "DELETE FROM
tblBorrowingRecords WHERE BookID_FK = @BookID"
cmd = New OleDbCommand(deleteRecordsSql, Con)
cmd.Parameters.AddWithValue("@BookID",
CInt(lblBookID.Text))
cmd.ExecuteNonQuery()
Dim sql As String = "DELETE FROM tblBooks WHERE BookID =
@BookID"
cmd = New OleDbCommand(sql, Con)
cmd.Parameters.AddWithValue("@BookID",
CInt(lblBookID.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("Book deleted successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadBooks()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error deleting book: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub dgvBooks_CellClick(sender As Object, e As
DataGridViewCellEventArgs) Handles dgvBooks.CellClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow = dgvBooks.Rows(e.RowIndex)
lblBookID.Text = row.Cells("BookID").Value.ToString()
txtTitle.Text = row.Cells("Title").Value.ToString()
txtAuthor.Text = row.Cells("Author").Value.ToString()
txtISBN.Text = row.Cells("ISBN").Value.ToString()
txtGenre.Text = row.Cells("Genre").Value.ToString()
txtTotalCopies.Text =
row.Cells("TotalCopies").Value.ToString()
txtAvailableCopies.Text =
row.Cells("AvailableCopies").Value.ToString()
btnAdd.Enabled = False
btnUpdate.Enabled = True
btnDelete.Enabled = True
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs)
Handles btnSearch.Click
LoadBooks(txtSearch.Text)
End Sub
Private Sub txtSearch_KeyPress(sender As Object, e As
KeyPressEventArgs) Handles txtSearch.KeyPress
If e.KeyChar = Chr(13) Then ' Enter key pressed
btnSearch.PerformClick()
e.Handled = True ' Prevent the beep sound
End If
End Sub
End Class
D. frmBorrowerRegistration.vb (Borrower Management Form)
1. Add a new "Windows Form" to your project. Name it frmBorrowerRegistration.vb.
2. Design frmBorrowerRegistration:
○ Labels: Student Name, Form, Contact Number, Email Address.
○ Textboxes: txtStudentName, txtForm, txtContactNumber, txtEmailAddress.
○ Buttons:
■ btnAdd (Text: "Add Borrower")
■ btnUpdate (Text: "Update Borrower")
■ btnDelete (Text: "Delete Borrower")
■ btnClear (Text: "Clear Fields")
■ btnSearch (Text: "Search")
○ Textbox for Search: txtSearch
○ DataGridView: dgvBorrowers.
○ Label: lblBorrowerID (to display the selected BorrowerID, hidden initially).
3. Code for frmBorrowerRegistration.vb:
Imports System.Data.OleDb
Public Class frmBorrowerRegistration
Private Sub frmBorrowerRegistration_Load(sender As Object, e As
EventArgs) Handles MyBase.Load
LoadBorrowers()
ClearFields()
lblBorrowerID.Visible = False ' Hide BorrowerID label
End Sub
Private Sub LoadBorrowers(Optional ByVal searchQuery As String =
"")
Try
OpenConnection()
Dim sql As String = "SELECT * FROM tblBorrowers"
If Not String.IsNullOrEmpty(searchQuery) Then
sql &= " WHERE StudentName LIKE '%" & searchQuery &
"%' OR Form LIKE '%" & searchQuery & "%' OR ContactNumber LIKE '%" &
searchQuery & "%'"
End If
da = New OleDbDataAdapter(sql, Con)
dt = New DataTable()
da.Fill(dt)
dgvBorrowers.DataSource = dt
dgvBorrowers.ReadOnly = True
dgvBorrowers.AllowUserToAddRows = False
Catch ex As Exception
MessageBox.Show("Error loading borrowers: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub ClearFields()
txtStudentName.Clear()
txtForm.Clear()
txtContactNumber.Clear()
txtEmailAddress.Clear()
lblBorrowerID.Text = ""
btnAdd.Enabled = True
btnUpdate.Enabled = False
btnDelete.Enabled = False
txtStudentName.Focus()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs)
Handles btnClear.Click
ClearFields()
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles
btnAdd.Click
' --- Validation ---
If String.IsNullOrWhiteSpace(txtStudentName.Text) OrElse
String.IsNullOrWhiteSpace(txtForm.Text) OrElse _
String.IsNullOrWhiteSpace(txtContactNumber.Text) Then
MessageBox.Show("Please fill in all mandatory fields
(Student Name, Form, Contact Number).", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Try
OpenConnection()
Dim sql As String = "INSERT INTO tblBorrowers
(StudentName, Form, ContactNumber, EmailAddress) VALUES (@StudentName,
@Form, @ContactNumber, @EmailAddress)"
cmd = New OleDbCommand(sql, Con)
cmd.Parameters.AddWithValue("@StudentName",
txtStudentName.Text)
cmd.Parameters.AddWithValue("@Form", txtForm.Text)
cmd.Parameters.AddWithValue("@ContactNumber",
txtContactNumber.Text)
cmd.Parameters.AddWithValue("@EmailAddress",
txtEmailAddress.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Borrower added successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadBorrowers()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error adding borrower: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs)
Handles btnUpdate.Click
If String.IsNullOrWhiteSpace(lblBorrowerID.Text) Then
MessageBox.Show("Please select a borrower to update.",
"Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
' --- Validation ---
If String.IsNullOrWhiteSpace(txtStudentName.Text) OrElse
String.IsNullOrWhiteSpace(txtForm.Text) OrElse _
String.IsNullOrWhiteSpace(txtContactNumber.Text) Then
MessageBox.Show("Please fill in all mandatory fields
(Student Name, Form, Contact Number).", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Try
OpenConnection()
Dim sql As String = "UPDATE tblBorrowers SET StudentName =
@StudentName, Form = @Form, ContactNumber = @ContactNumber,
EmailAddress = @EmailAddress WHERE BorrowerID = @BorrowerID"
cmd = New OleDbCommand(sql, Con)
cmd.Parameters.AddWithValue("@StudentName",
txtStudentName.Text)
cmd.Parameters.AddWithValue("@Form", txtForm.Text)
cmd.Parameters.AddWithValue("@ContactNumber",
txtContactNumber.Text)
cmd.Parameters.AddWithValue("@EmailAddress",
txtEmailAddress.Text)
cmd.Parameters.AddWithValue("@BorrowerID",
CInt(lblBorrowerID.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("Borrower updated successfully!",
"Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadBorrowers()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error updating borrower: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs)
Handles btnDelete.Click
If String.IsNullOrWhiteSpace(lblBorrowerID.Text) Then
MessageBox.Show("Please select a borrower to delete.",
"Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
If MessageBox.Show("Are you sure you want to delete this
borrower? All their borrowing records will also be affected.",
"Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) =
DialogResult.No Then
Return
End If
Try
OpenConnection()
' Optional: Check if the borrower has any unreturned books
before allowing deletion
Dim borrowedCount As Integer = 0
Dim checkBorrowedSql As String = "SELECT COUNT(*) FROM
tblBorrowingRecords WHERE BorrowerID_FK = @BorrowerID AND ReturnDate
IS NULL"
cmd = New OleDbCommand(checkBorrowedSql, Con)
cmd.Parameters.AddWithValue("@BorrowerID",
CInt(lblBorrowerID.Text))
Dim result As Object = cmd.ExecuteScalar()
If result IsNot DBNull.Value Then
borrowedCount = CInt(result)
End If
If borrowedCount > 0 Then
MessageBox.Show("Cannot delete borrower: This borrower
has " & borrowedCount & " unreturned books. Please ensure all books
are returned.", "Deletion Blocked", MessageBoxButtons.OK,
MessageBoxIcon.Warning)
Return
End If
' Delete associated borrowing records first due to
referential integrity
Dim deleteRecordsSql As String = "DELETE FROM
tblBorrowingRecords WHERE BorrowerID_FK = @BorrowerID"
cmd = New OleDbCommand(deleteRecordsSql, Con)
cmd.Parameters.AddWithValue("@BorrowerID",
CInt(lblBorrowerID.Text))
cmd.ExecuteNonQuery()
Dim sql As String = "DELETE FROM tblBorrowers WHERE
BorrowerID = @BorrowerID"
cmd = New OleDbCommand(sql, Con)
cmd.Parameters.AddWithValue("@BorrowerID",
CInt(lblBorrowerID.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("Borrower deleted successfully!",
"Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadBorrowers()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error deleting borrower: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub dgvBorrowers_CellClick(sender As Object, e As
DataGridViewCellEventArgs) Handles dgvBorrowers.CellClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow = dgvBorrowers.Rows(e.RowIndex)
lblBorrowerID.Text =
row.Cells("BorrowerID").Value.ToString()
txtStudentName.Text =
row.Cells("StudentName").Value.ToString()
txtForm.Text = row.Cells("Form").Value.ToString()
txtContactNumber.Text =
row.Cells("ContactNumber").Value.ToString()
txtEmailAddress.Text =
row.Cells("EmailAddress").Value.ToString()
btnAdd.Enabled = False
btnUpdate.Enabled = True
btnDelete.Enabled = True
End If
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs)
Handles btnSearch.Click
LoadBorrowers(txtSearch.Text)
End Sub
Private Sub txtSearch_KeyPress(sender As Object, e As
KeyPressEventArgs) Handles txtSearch.KeyPress
If e.KeyChar = Chr(13) Then ' Enter key pressed
btnSearch.PerformClick()
e.Handled = True ' Prevent the beep sound
End If
End Sub
End Class
E. frmBorrowReturn.vb (Borrow/Return Transaction Form)
1. Add a new "Windows Form" to your project. Name it frmBorrowReturn.vb.
2. Design frmBorrowReturn:
○ Labels: Book Title, Borrower Name, Borrow Date, Due Date, Return Date.
○ ComboBoxes: cboBook (for selecting books), cboBorrower (for selecting
borrowers).
○ DateTimePicker: dtpBorrowDate, dtpDueDate, dtpReturnDate.
○ Buttons:
■ btnBorrow (Text: "Borrow Book")
■ btnReturn (Text: "Return Book")
■ btnClear (Text: "Clear Fields")
○ DataGridView: dgvCurrentBorrows (to show active borrowed books).
○ Labels (hidden, for IDs): lblSelectedBookID, lblSelectedBorrowerID,
lblSelectedRecordID
3. Code for frmBorrowReturn.vb:
Imports System.Data.OleDb
Public Class frmBorrowReturn
Private Sub frmBorrowReturn_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
LoadComboBoxes()
LoadCurrentBorrows()
ClearFields()
dtpBorrowDate.Value = Date.Today
dtpDueDate.Value = Date.Today.AddDays(14) ' Default due date 2
weeks from borrow
lblSelectedBookID.Visible = False
lblSelectedBorrowerID.Visible = False
lblSelectedRecordID.Visible = False
End Sub
Private Sub LoadComboBoxes()
Try
OpenConnection()
' Load Books into ComboBox
Dim bookSql As String = "SELECT BookID, Title,
AvailableCopies FROM tblBooks WHERE AvailableCopies > 0 ORDER BY
Title"
da = New OleDbDataAdapter(bookSql, Con)
Dim bookDt As New DataTable()
da.Fill(bookDt)
cboBook.DataSource = bookDt
cboBook.DisplayMember = "Title"
cboBook.ValueMember = "BookID"
cboBook.SelectedIndex = -1 ' No selection initially
' Load Borrowers into ComboBox
Dim borrowerSql As String = "SELECT BorrowerID,
StudentName FROM tblBorrowers ORDER BY StudentName"
da = New OleDbDataAdapter(borrowerSql, Con)
Dim borrowerDt As New DataTable()
da.Fill(borrowerDt)
cboBorrower.DataSource = borrowerDt
cboBorrower.DisplayMember = "StudentName"
cboBorrower.ValueMember = "BorrowerID"
cboBorrower.SelectedIndex = -1 ' No selection initially
Catch ex As Exception
MessageBox.Show("Error loading combo boxes: " &
ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub LoadCurrentBorrows()
Try
OpenConnection()
Dim sql As String = "SELECT T.RecordID, B.Title,
BR.StudentName, T.BorrowDate, T.DueDate " & _
"FROM (tblBorrowingRecords AS T INNER
JOIN tblBooks AS B ON T.BookID_FK = B.BookID) " & _
"INNER JOIN tblBorrowers AS BR ON
T.BorrowerID_FK = BR.BorrowerID " & _
"WHERE T.ReturnDate IS NULL ORDER BY
T.BorrowDate DESC"
da = New OleDbDataAdapter(sql, Con)
dt = New DataTable()
da.Fill(dt)
dgvCurrentBorrows.DataSource = dt
dgvCurrentBorrows.ReadOnly = True
dgvCurrentBorrows.AllowUserToAddRows = False
' Highlight overdue books in DataGridView
For Each row As DataGridViewRow In dgvCurrentBorrows.Rows
If row.Cells("DueDate").Value IsNot DBNull.Value Then
Dim dueDate As DateTime =
CDate(row.Cells("DueDate").Value)
If Date.Today > dueDate Then
row.DefaultCellStyle.BackColor =
Color.LightCoral ' Light red for overdue
Else
row.DefaultCellStyle.BackColor =
Color.LightGreen ' Light green for not overdue
End If
End If
Next
Catch ex As Exception
MessageBox.Show("Error loading current borrows: " &
ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub ClearFields()
cboBook.SelectedIndex = -1
cboBorrower.SelectedIndex = -1
dtpBorrowDate.Value = Date.Today
dtpDueDate.Value = Date.Today.AddDays(14)
dtpReturnDate.Value = Date.Today
dtpReturnDate.Enabled = False ' Disable return date initially
for new borrow
lblSelectedBookID.Text = ""
lblSelectedBorrowerID.Text = ""
lblSelectedRecordID.Text = ""
btnBorrow.Enabled = True
btnReturn.Enabled = False
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs)
Handles btnClear.Click
ClearFields()
End Sub
Private Sub btnBorrow_Click(sender As Object, e As EventArgs)
Handles btnBorrow.Click
' --- Validation ---
If cboBook.SelectedIndex = -1 Then
MessageBox.Show("Please select a book.", "Validation
Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
If cboBorrower.SelectedIndex = -1 Then
MessageBox.Show("Please select a borrower.", "Validation
Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
If dtpBorrowDate.Value > Date.Today Then
MessageBox.Show("Borrow Date cannot be in the future.",
"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
If dtpDueDate.Value < dtpBorrowDate.Value Then
MessageBox.Show("Due Date cannot be before Borrow Date.",
"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Dim bookID As Integer = CInt(cboBook.SelectedValue)
Dim borrowerID As Integer = CInt(cboBorrower.SelectedValue)
Try
OpenConnection()
' Check if book is actually available
Dim availableCopies As Integer = 0
Dim checkSql As String = "SELECT AvailableCopies FROM
tblBooks WHERE BookID = @BookID"
cmd = New OleDbCommand(checkSql, Con)
cmd.Parameters.AddWithValue("@BookID", bookID)
Dim result As Object = cmd.ExecuteScalar()
If result IsNot DBNull.Value Then
availableCopies = CInt(result)
End If
If availableCopies <= 0 Then
MessageBox.Show("No copies of this book are currently
available for borrowing.", "Not Available", MessageBoxButtons.OK,
MessageBoxIcon.Warning)
Return
End If
' Insert into BorrowingRecords
Dim borrowSql As String = "INSERT INTO tblBorrowingRecords
(BookID_FK, BorrowerID_FK, BorrowDate, DueDate) VALUES (@BookID_FK,
@BorrowerID_FK, @BorrowDate, @DueDate)"
cmd = New OleDbCommand(borrowSql, Con)
cmd.Parameters.AddWithValue("@BookID_FK", bookID)
cmd.Parameters.AddWithValue("@BorrowerID_FK", borrowerID)
cmd.Parameters.AddWithValue("@BorrowDate",
dtpBorrowDate.Value.ToShortDateString())
cmd.Parameters.AddWithValue("@DueDate",
dtpDueDate.Value.ToShortDateString())
cmd.ExecuteNonQuery()
' Update AvailableCopies in tblBooks
Dim updateBookSql As String = "UPDATE tblBooks SET
AvailableCopies = AvailableCopies - 1 WHERE BookID = @BookID"
cmd = New OleDbCommand(updateBookSql, Con)
cmd.Parameters.AddWithValue("@BookID", bookID)
cmd.ExecuteNonQuery()
MessageBox.Show("Book borrowed successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadComboBoxes() ' Refresh available books
LoadCurrentBorrows()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error borrowing book: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Handles btnReturn.Click
If String.IsNullOrWhiteSpace(lblSelectedRecordID.Text) Then
MessageBox.Show("Please select a borrowed book from the
list to return.", "Selection Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning)
Return
End If
Dim recordID As Integer = CInt(lblSelectedRecordID.Text)
Dim bookID As Integer = CInt(lblSelectedBookID.Text) ' Get
BookID from stored label
Dim borrowerID As Integer = CInt(lblSelectedBorrowerID.Text) '
Get BorrowerID from stored label
' --- Validation ---
If dtpReturnDate.Value < dtpBorrowDate.Value Then
MessageBox.Show("Return Date cannot be before Borrow
Date.", "Validation Error", MessageBoxButtons.OK,
MessageBoxIcon.Warning)
Return
End If
If dtpReturnDate.Value > Date.Today Then
MessageBox.Show("Return Date cannot be in the future.",
"Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Try
OpenConnection()
' Update ReturnDate in tblBorrowingRecords
Dim returnSql As String = "UPDATE tblBorrowingRecords SET
ReturnDate = @ReturnDate WHERE RecordID = @RecordID"
cmd = New OleDbCommand(returnSql, Con)
cmd.Parameters.AddWithValue("@ReturnDate",
dtpReturnDate.Value.ToShortDateString())
cmd.Parameters.AddWithValue("@RecordID", recordID)
cmd.ExecuteNonQuery()
' Update AvailableCopies in tblBooks
Dim updateBookSql As String = "UPDATE tblBooks SET
AvailableCopies = AvailableCopies + 1 WHERE BookID = @BookID"
cmd = New OleDbCommand(updateBookSql, Con)
cmd.Parameters.AddWithValue("@BookID", bookID)
cmd.ExecuteNonQuery()
MessageBox.Show("Book returned successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information)
LoadComboBoxes() ' Refresh available books
LoadCurrentBorrows()
ClearFields()
Catch ex As Exception
MessageBox.Show("Error returning book: " & ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End Sub
Private Sub dgvCurrentBorrows_CellClick(sender As Object, e As
DataGridViewCellEventArgs) Handles dgvCurrentBorrows.CellClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow =
dgvCurrentBorrows.Rows(e.RowIndex)
lblSelectedRecordID.Text =
row.Cells("RecordID").Value.ToString() ' Assuming RecordID is in the
DGV
' You'll need to retrieve BookID_FK and BorrowerID_FK from
the database if they are not in the DGV
' For simplicity, if your DGV query includes them, you can
directly access.
' Otherwise, fetch them from the database using RecordID.
Try
OpenConnection()
Dim sql As String = "SELECT BookID_FK, BorrowerID_FK,
BorrowDate, DueDate FROM tblBorrowingRecords WHERE RecordID =
@RecordID"
cmd = New OleDbCommand(sql, Con)
cmd.Parameters.AddWithValue("@RecordID",
CInt(lblSelectedRecordID.Text))
Dim reader As OleDbDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblSelectedBookID.Text =
reader("BookID_FK").ToString()
lblSelectedBorrowerID.Text =
reader("BorrowerID_FK").ToString()
dtpBorrowDate.Value = CDate(reader("BorrowDate"))
dtpDueDate.Value = CDate(reader("DueDate"))
End If
reader.Close()
' Set combo boxes to selected values
cboBook.SelectedValue = CInt(lblSelectedBookID.Text)
cboBorrower.SelectedValue =
CInt(lblSelectedBorrowerID.Text)
dtpReturnDate.Value = Date.Today ' Default return date
to today
dtpReturnDate.Enabled = True ' Enable return date
btnBorrow.Enabled = False
btnReturn.Enabled = True
Catch ex As Exception
MessageBox.Show("Error loading selected borrow record:
" & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
CloseConnection()
End Try
End If
End Sub
End Class
Running Your Project:
1. Create the LibraryDB.accdb file in MS Access, following the table and relationship
designs above.
2. Save LibraryDB.accdb into your Visual Basic project's bin\Debug folder (e.g.,
C:\YourProjectFolder\LibraryManagementSystemVB\bin\Debug\LibraryDB.accdb).
3. Open your Visual Basic project in Visual Studio.
4. Add all forms and the module to your project.
5. Design your forms by dragging and dropping controls from the Toolbox as described.
6. Copy and paste the respective VB.NET code into the code view for each form and the
module.
7. Set frmMainMDI as the Startup Form in your Project Properties.
8. Run (Start Debugging) the project (F5).
This setup provides a solid foundation for your Zimsec O-Level Computer Science project,
demonstrating database management, GUI development, and data manipulation. Remember to
test thoroughly and add more comprehensive error handling and validation as you progress!