簡體   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