Deleting Data in VB.Net and SQL Server 2018 Database
Submitted by janobe on Monday, October 21, 2019 - 19:13.
This is the continuation of my previous tutorial which is Updating Data in VB.Net and SQL Server 2018. This time, we will add the delete method in the application that we made last time. This functionality will help you to delete the selected data in the datagridview and it will also automatically delete the data in the SQL Server database when the button is clicked. Let's begin.
Output
The complete source code is included. You can download it and run it on your computer.
For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.
Creating Application
Step 1
Open Retrieving Data in VB.Net and SQL Server 2018.Step 2
Add a button in the Form and name it “Delete”. Then, sdesign the Form just like shown below.Step 3
Press F7 to open the code editor. In the code editor, add a method for deleting the data in the database.- Private Sub deleteData(sql As String)
- Try
- con.Open()
- cmd = New SqlCommand
- With cmd
- .Connection = con
- .CommandText = sql
- result = .ExecuteNonQuery()
- End With
- If result > 0 Then
- MsgBox("Data has been deleted in the database")
- End If
- Catch ex As Exception
- MsgBox(ex.Message)
- Finally
- con.Close()
- End Try
- End Sub
Step 4
Go back to the design view, double click the “Delete” button to open theclick event
handler of it. After that, add this code inside the “Button4_Click” event to delete the data in the database.
- Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
- sql = "Delete FROM tblperson WHERE PersonID=" & DataGridView1.CurrentRow.Cells(0).Value
- deleteData(sql)
- End Sub
Add new comment
- 2283 views