简体   繁体   中英

Delete a DataTable row, source of selected DataGridView row, on button click

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.

看起来像什么

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

如果您只想删除单个选定的行

DataGridView1.CurrentRow.Delete()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM