0% found this document useful (0 votes)
17 views2 pages

Update Button

Uploaded by

bokamuso100
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)
17 views2 pages

Update Button

Uploaded by

bokamuso100
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/ 2

r SQLite?

Let me know and I can assist further!

Imports System.Data.SqlClient

Public Class Form1


Dim connectionString As String = "Data Source=.\SQLEXPRESS;Initial
Catalog=YourDatabaseName;Integrated Security=True"

' Load data on form load


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadData()
End Sub

' Load data into DataGridView


Private Sub LoadData()
Using con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand("SELECT * FROM Books", con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
DataGridView1.DataSource = table
End Using
End Sub

' Fill textboxes when a row is selected


Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles
DataGridView1.CellClick
If e.RowIndex >= 0 Then
Dim row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
txtbn.Text = row.Cells("BookName").Value.ToString()
txtAuthor.Text = row.Cells("Author").Value.ToString()
txtYear.Text = row.Cells("YearPublished").Value.ToString()
End If
End Sub

' Update button click


Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
If DataGridView1.CurrentRow Is Nothing Then
MessageBox.Show("Please select a row to update.")
Return
End If

Dim bookID As Integer = Convert.ToInt32(DataGridView1.CurrentRow.Cells("BookID").Value)

Using con As New SqlConnection(connectionString)


Dim query As String = "UPDATE Books SET BookName = @bn, Author = @auth, YearPublished
= @yr WHERE BookID = @id"
Dim cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@bn", txtbn.Text)
cmd.Parameters.AddWithValue("@auth", txtAuthor.Text)
cmd.Parameters.AddWithValue("@yr", txtYear.Text)
cmd.Parameters.AddWithValue("@id", bookID)

con.Open()
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
con.Close()

If rowsAffected > 0 Then


MessageBox.Show("Record updated successfully.")
LoadData()
Else
MessageBox.Show("Update failed.")
End If
End Using
End Sub
End Class

You might also like