Reputation: 455
I have this DataTable called ProductTable
that have 3 columns that serves as the source for the DataGridView ProductGrid
.
When clicking on the button DeleteRow
, the user should delete the row in ProductTable
that correspond the selected row in ProductGrid
I tried with
Private Sub DeleteRow_Click(sender As Object, e As EventArgs) Handles DeleteRow.Click
Dim i As Integer
For i = 0 To 100
Try
ProductTable.Rows(i).Delete()
Catch ex As Exception
End Try
Next
End Sub
But I'm missing something obvious : The condition that allows me to pick the row in the DataTable that would correspond to ProductGrid.SelectedCells(0).Value.ToString()
.
But I don't know how to do it, as ProductTable.Rows(i).Columns(0).Value
doesn't work since Columns
isn't a member of the Row
object.
Upvotes: 0
Views: 1085
Reputation: 9479
You may have a problem deleting a row from the bound DataTable
using the grids “selected” row index if the grid is “Sorted or Filtered”. I am betting the wrong rows will get deleted from the DataTable
when the grid is sorted or filtered.
To fix this, I suggest using the grids DataBoundItem
from the selected row. This should ensure the proper row is removed from the DataTable
. Something like below…
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
if (DataGridView1.SelectedRows.Count() > 0) Then
Dim row As DataGridViewRow = DataGridView1.SelectedRows(0)
If (Not row.IsNewRow) Then
row.DataBoundItem.Delete
' You can also directly delete the row from the grids rows collection
' which will automatically map to the proper row in the table
'DataGridView1.Rows.RemoveAt(row.Index)
End If
End If
End Sub
Upvotes: 3
Reputation: 23
If you just want to delete single selected row
DataGridView1.CurrentRow.Delete()
Upvotes: 1