SqlDataAdapter缺少DeleteCommand

时间:2014-12-02 20:43:35

标签: vb.net datagridview

我正在使用DataGridView加载一个VB.NET SqlDataAdapter来填充DataSet,然后将DataSource的{​​{1}}设置为DataGridView 1}}。

出于某种原因,使用DataSet填充的唯一命令是SqlCommandBuilder。我意识到我只是指定了一个SELECT查询,但我认为SelectCommand的目的是为我生成更新/删除/插入命令。

以下是适用的代码:

SqlCommandBuilder

当我删除一行时,它会从Dim _dstErrorLog As New DataSet Dim _adapter As SqlDataAdapter Dim _builder As SqlCommandBuilder Private Sub ErrorLog_Load(sender As Object, e As EventArgs) Handles MyBase.Load Call LoadErrorLog() End Sub Private Sub LoadErrorLog() Dim strSql As String strSql = "SELECT Ident, LogDate, LogDesc FROM dbo.ErrorLog ORDER BY DescDateTime DESC" _adapter = New SqlDataAdapter(strSql, dataLayer.Connection) _builder = New SqlCommandBuilder(_adapter) _adapter.Fill(_dstErrorLog) grdErrorLog.DataSource = _dstErrorLog.Tables(0) End Sub Private Sub grdErrorLog_UserDeletingRow(sender As Object, e As DataGridViewRowCancelEventArgs) Handles grdErrorLog.UserDeletingRow _adapter.Update(_dstErrorLog.Tables(0)) End Sub 中消失,但是当我重新打开表单时,数据仍然存在。我需要自己指定DataGridView吗?如果是这样,那么DeleteCommand ??

的目的是什么

1 个答案:

答案 0 :(得分:1)

使用 UserDeletedRow 事件,而不是 UserDeletingRow
在UserDeletingRow事件中,对DataGridView所做的更改仍未提交到绑定的DataSource,因此在该事件中调用 SqlDataAdapter.Update 并不会导致对数据库的任何更改,因为该表仍未改变。

Private Sub grdErrorLog_UserDeletedRow(sender As Object, e As DataGridViewRowEventArgs) Handles grdErrorLog.UserDeletingRow
    Dim count = _adapter.Update(_dstErrorLog.Tables(0))
    Console.WriteLine("Rows deleted:" & Count)
End Sub

事实上 UserDeletingRow ,参数eDataGridViewRowCancelEventArgs,这意味着您仍然可以取消删除设置e.Cancel = True