[英]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
. 我有一个称为
ProductTable
DataTable,它具有3列,作为DataGridView ProductGrid
的源。
When clicking on the button DeleteRow
, the user should delete the row in ProductTable
that correspond the selected row in ProductGrid
当单击按钮
DeleteRow
,用户应删除ProductTable
中与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()
. 但是我缺少明显的东西:这种条件使我可以在DataTable中选择与
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. 但是我不知道该怎么做,因为
ProductTable.Rows(i).Columns(0).Value
不起作用,因为Columns
不是Row
对象的成员。
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”. 如果网格为“已排序或已过滤”,则可能会使用网格“选定的”行索引从绑定的
DataTable
删除行时遇到问题。 I am betting the wrong rows will get deleted from the DataTable
when the grid is sorted or filtered. 我
DataTable
当对网格进行排序或过滤时,错误的行将从DataTable
删除。
To fix this, I suggest using the grids DataBoundItem
from the selected row. 要解决此问题,我建议使用所选行中的网格
DataBoundItem
。 This should ensure the proper row is removed from the DataTable
. 这应该确保从
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.