Deleting Data in VB.Net and SQL Server 2018 Database

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.

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. figure 1

Step 3

Press F7 to open the code editor. In the code editor, add a method for deleting the data in the database.
  1.        
  2.     Private Sub deleteData(sql As String)
  3.         Try
  4.             con.Open()
  5.             cmd = New SqlCommand
  6.             With cmd
  7.                 .Connection = con
  8.                 .CommandText = sql
  9.                 result = .ExecuteNonQuery()
  10.             End With
  11.             If result > 0 Then
  12.                 MsgBox("Data has been deleted in the database")
  13.             End If
  14.  
  15.         Catch ex As Exception
  16.             MsgBox(ex.Message)
  17.         Finally
  18.             con.Close()
  19.         End Try
  20.     End Sub

Step 4

Go back to the design view, double click the “Delete” button to open the click event handler of it. After that, add this code inside the “Button4_Click” event to delete the data in the database.
  1.    
  2.     Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
  3.         sql = "Delete FROM tblperson WHERE PersonID=" & DataGridView1.CurrentRow.Cells(0).Value
  4.         deleteData(sql)
  5.     End Sub
Output figure 2 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.

Add new comment