In this Video I will explain, how to delete Rows from DataGridView and Database in Windows (WinForms) Application using VB.Net.
When the Delete Button is clicked, a Confirmation MessageBox will be displayed and if the User clicks Yes button the Row will be deleted from DataGridView and Database using VB.Net.
: Source Code
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Const conn1 As String = "data source=.;initial catalog=users;integrated security=true"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
bindgridview()
End Sub
Private Sub bindgridview()
DataGridView1.AllowUserToAddRows = False
DataGridView1.Columns.Clear()
Dim id As DataGridViewColumn = New DataGridViewTextBoxColumn
id.Name = "id"
id.HeaderText = "ID"
id.DataPropertyName = "id"
id.Width = 70
DataGridView1.Columns.Insert(0, id)
Dim name As DataGridViewColumn = New DataGridViewTextBoxColumn
name.Name = "name"
name.HeaderText = "name"
name.DataPropertyName = "name"
name.Width = 100
DataGridView1.Columns.Insert(1, name)
Dim country As DataGridViewColumn = New DataGridViewTextBoxColumn
country.Name = "country"
country.HeaderText = "country"
country.DataPropertyName = "country"
country.Width = 100
DataGridView1.Columns.Insert(2, country)
DataGridView1.DataSource = Nothing
Using con As SqlConnection = New SqlConnection(conn1)
Using cmd As SqlCommand = New SqlCommand("Select id,name,country from table1", con)
cmd.CommandType = CommandType.Text
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable
sda.Fill(dt)
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Using
Dim buttoncolumn As DataGridViewButtonColumn = New DataGridViewButtonColumn
buttoncolumn.HeaderText = ""
buttoncolumn.Width = 100
buttoncolumn.Name = "buttoncolumn"
buttoncolumn.Text = "Delete"
buttoncolumn.UseColumnTextForButtonValue = True
DataGridView1.Columns.Insert(3, buttoncolumn)
End Sub
Private Sub DataGridView1_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.ColumnIndex = 3 Then
Dim row1 As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
If MessageBox.Show(String.Format("Do you want to delete id:{0}", row1.Cells("id").Value), "confirmation", MessageBoxButtons.OKCancel) = DialogResult.OK Then
Using con As New SqlConnection(conn1)
Using cmd As New SqlCommand("delete from table1 where id=@id", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@id", row1.Cells("id").Value)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Me.bindgridview()
End Using
End Using
End If
End If
End Sub
End Class
No comments:
Post a Comment