why can't my datagridview delete from datagridviewcolumnlink with event CellContentClick in vb.net?
I want to delete the selected rows with datagridview column link. I tried to click in the link column there was no event whatsoever but if I tried with the button event then it worked as the code below
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If DataGridView1.SelectedRows.Count = 0 Then
Return
End If
If MessageBox.Show("Delete selected record?", "CONFIRM!", MessageBoxButtons.YesNoCancel) = DialogResult.Yes Then
For Each row As DataGridViewRow In DataGridView1.SelectedRows
DataGridView1.Rows.RemoveAt(row.Index)
Next row
End If
End Sub
is there something wrong with my code please guide me
Thanks
Private table1 As New DataTable
Public Property AllowDelete() As Boolean = True
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
table1.Columns.Add(New DataColumn("Column1", GetType(String)))
table1.Columns.Add(New DataColumn("Column2", GetType(String)))
table1.Columns.Add(New DataColumn("Column3", GetType(String)))
table1.Columns.Add(New DataColumn("Column4", GetType(String)))
table1.Rows.Add("1", "1", "1", "X")
table1.Rows.Add("2", "2", "2", "X")
table1.Rows.Add("3", "3", "3", "X")
table1.Rows.Add("4", "4", "4", "X")
DataGridView1.ReadOnly = True
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
ColDel.Visible = Me.AllowDelete
DataGridView1.AllowUserToDeleteRows = ColDel.Visible
DataGridView1.DataSource = table1
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.ColumnIndex = ColDel.Index Then
If DataGridView1.SelectedRows.Count = 0 Then
Return
End If
If MessageBox.Show("Delete selected record?", "CONFIRM!", MessageBoxButtons.YesNoCancel) = DialogResult.Yes Then
For Each row As DataGridViewRow In DataGridView1.SelectedRows
DataGridView1.Rows.RemoveAt(row.Index)
Next row
End If
End If
End Sub
As I said in the comment, use e.ColumnIndex
to make sure the cell that the event was raised for is in the correct column and then use e.RowIndex
to get the row to remove:
If e.ColumnIndex = 3 Then
DataGridView1.Rows.RemoveAt(e.RowIndex)
End If