0% found this document useful (0 votes)
2 views6 pages

Code For CRUD Form

The document contains a Visual Basic .NET class for a CRUD (Create, Read, Update, Delete) application that interacts with an Access database. It includes methods for loading data, saving new records, updating existing records, deleting records, and searching by Student ID. The class also manages user interface interactions with buttons and a DataGridView for displaying and manipulating student data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Code For CRUD Form

The document contains a Visual Basic .NET class for a CRUD (Create, Read, Update, Delete) application that interacts with an Access database. It includes methods for loading data, saving new records, updating existing records, deleting records, and searching by Student ID. The class also manages user interface interactions with buttons and a DataGridView for displaying and manipulating student data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Code for CRUD form

Imports System.Data.OleDb
Public Class CRUD
Dim con As OleDbConnection
Dim adapter As OleDbDataAdapter
Dim dataset As DataSet
Dim bindingSource As BindingSource
Dim cmd As OleDbCommand
Dim currentPosition As Integer = 0

Private Sub CRUD_Load(sender As Object, e As EventArgs) Handles MyBase.Load


con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=|
DataDirectory|\CRUD.mdb")
' Initialize DataGridView
dgvCRUD.AutoGenerateColumns = True
' Load data from database
LoadData()
End Sub
Private Sub LoadData()
' Initialize dataset and adapter
dataset = New DataSet
adapter = New OleDbDataAdapter("SELECT * FROM FORM3", con)
' Fill dataset
adapter.Fill(dataset, "FORM3")
' Initialize binding source
bindingSource = New BindingSource
bindingSource.DataSource = dataset.Tables("FORM3")
' Bind data to DataGridView
dgvCRUD.DataSource = bindingSource
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
' Check if the StudentID already exists
If DoesStudentIDExist(txtStudentID.Text) Then
MessageBox.Show("This Student ID already exists. Please enter a unique Student ID.")
Return
End If
' Insert data into database
cmd = New OleDbCommand("INSERT INTO FORM3 (StudentID, FName, Surname,
Class, Age, EnrollDate) VALUES (@StudentID, @FName, @Surname, @Class, @Age,
@EnrollDate)", con)
cmd.Parameters.AddWithValue("@StudentID", txtStudentID.Text)
cmd.Parameters.AddWithValue("@FName", txtFName.Text)
cmd.Parameters.AddWithValue("@Surname", txtSurname.Text)
cmd.Parameters.AddWithValue("@Class", cmbClass.SelectedItem)
cmd.Parameters.AddWithValue("@Age", txtAge.Text)
cmd.Parameters.AddWithValue("@EnrollDate", EnrollDate.Text)

' Open the connection, execute the command, and close the connection
con.Open()
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
con.Close()

' Check if any rows were updated


If rowsAffected > 0 Then
MessageBox.Show("Record saved successfully.", "Success", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Else
MessageBox.Show("Record not saved.", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
End If

' Reload data


LoadData()

End Sub

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click

Try
' Create the SQL command to update data in the database
cmd = New OleDbCommand("UPDATE FORM3 SET FName = @FName, Surname =
@Surname, Class = @Class, Age = @Age, EnrollDate = @EnrollDate WHERE StudentID =
@StudentID", con)

' Set parameter values


cmd.Parameters.AddWithValue("@FName", txtFName.Text)
cmd.Parameters.AddWithValue("@Surname", txtSurname.Text)
cmd.Parameters.AddWithValue("@Class", cmbClass.SelectedItem)
cmd.Parameters.AddWithValue("@Age", txtAge.Text)
cmd.Parameters.AddWithValue("@EnrollDate", EnrollDate.Text)
cmd.Parameters.AddWithValue("@StudentID", txtStudentID.Text)

' Open the connection, execute the command, and close the connection
con.Open()
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
con.Close()

' Check if any rows were updated


If rowsAffected > 0 Then
MessageBox.Show("Record updated successfully.", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("No record found with that Student ID.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If

' Reload data


LoadData()

Catch ex As Exception
MessageBox.Show("An error occurred: " & ex.Message)
Finally
' Ensure the connection is closed in case of an error
If con.State = ConnectionState.Open Then
con.Close()
End If
End Try
End Sub

Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click


' Delete data from database
cmd = New OleDbCommand("DELETE FROM FORM3 WHERE StudentID =
@StudentID", con)

' Set the parameter value


cmd.Parameters.AddWithValue("@StudentID", txtStudentID.Text)

' Open the connection, execute the command, and close the connection
con.Open()
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
con.Close()

' Check if any rows were updated


If rowsAffected > 0 Then
MessageBox.Show("Record deleted successfully.", "Success", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Else
MessageBox.Show("Record not deleted.", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
End If

' Reload data


LoadData()
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click

'Navigate to next record


If currentPosition < dataset.Tables("FORM3").Rows.Count - 1 Then
currentPosition += 1
bindingSource.Position = currentPosition
End If
End Sub

Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click


' Navigate to previous record
If currentPosition > 0 Then
currentPosition -= 1
bindingSource.Position = currentPosition
End If
End Sub

Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click


Me.Close()
Main.Show()
End Sub

Private Sub dgvCRUD_CellContentClick(sender As Object, e As


DataGridViewCellEventArgs) Handles dgvCRUD.CellContentClick
Dim selectedrow As DataGridViewRow
selectedrow = dgvCRUD.Rows(e.RowIndex)
txtStudentID.Text = selectedrow.Cells(0).Value
txtFName.Text = selectedrow.Cells(1).Value
txtSurname.Text = selectedrow.Cells(2).Value
cmbClass.Text = selectedrow.Cells(3).Value
txtAge.Text = selectedrow.Cells(4).Value
EnrollDate.Value = selectedrow.Cells(5).Value

End Sub

Private Function DoesStudentIDExist(studentID As String) As Boolean


Dim exists As Boolean = False
Try
' Create the SQL command to check for existing StudentID
cmd = New OleDbCommand("SELECT COUNT(*) FROM FORM3 WHERE StudentID
= @StudentID", con)
cmd.Parameters.AddWithValue("@StudentID", studentID)
con.Open()
Dim count As Integer = Convert.ToInt32(cmd.ExecuteScalar())
exists = (count > 0)
Catch ex As Exception
MessageBox.Show("An error occurred while checking for existing Student ID: " &
ex.Message)
Finally
If con.State = ConnectionState.Open Then
con.Close()
End If
End Try
Return exists
End Function

Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click


' Check if the txtSearch textbox is empty
If String.IsNullOrWhiteSpace(txtSearch.Text) Then
' Reload all data into the DataGridView
LoadData()
Return
End If

' Query to search for the specific StudentID


Dim query As String = "SELECT * FROM FORM3 WHERE StudentID = @StudentID"

' Create a new DataSet to hold the search results


Dim searchDataset As New DataSet()

Try
' Initialize the adapter with the search query
adapter = New OleDbDataAdapter(query, con)

' Add the parameter for StudentID


adapter.SelectCommand.Parameters.AddWithValue("@StudentID", txtSearch.Text)

' Fill the search results into the dataset


adapter.Fill(searchDataset, "FORM3")

' Check if any rows were returned


If searchDataset.Tables("FORM3").Rows.Count > 0 Then
' Bind the search results to the DataGridView
dgvCRUD.DataSource = searchDataset.Tables("FORM3")
Else
MessageBox.Show("No student found with the given Student ID.", "No Results",
MessageBoxButtons.OK, MessageBoxIcon.Information)
' Optionally reload all data if no results are found
LoadData()
End If
Catch ex As Exception
MessageBox.Show("An error occurred while searching: " & ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub

Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click


txtStudentID.Clear()
txtAge.Clear()
txtFName.Clear()
txtSurname.Clear()
txtSearch.Clear()
txtStudentID.Clear()
cmbClass.SelectedIndex = -1
EnrollDate.Text = Date.Now
LoadData()
End Sub
End Class

You might also like