繁体   English   中英

删除DataTable行,选定DataGridView行的源,单击按钮

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

我有一个称为ProductTable DataTable,它具有3列,作为DataGridView ProductGrid的源。

当单击按钮DeleteRow ,用户应删除ProductTable中与ProductGrid选定行相对应的行。

我尝试过

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

但是我缺少明显的东西:这种条件使我可以在DataTable中选择与ProductGrid.SelectedCells(0).Value.ToString()对应的行。

但是我不知道该怎么做,因为ProductTable.Rows(i).Columns(0).Value不起作用,因为Columns不是Row对象的成员。

看起来像什么

如果网格为“已排序或已过滤”,则可能会使用网格“选定的”行索引从绑定的DataTable删除行时遇到问题。 DataTable当对网格进行排序或过滤时,错误的行将从DataTable删除。

要解决此问题,我建议使用所选行中的网格DataBoundItem 这应该确保从DataTable删除了正确的行。 像下面这样...

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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