【问题标题】:Deleting a record from dataset and sql server从数据集和 sql server 中删除记录
【发布时间】:2013-02-12 12:51:33
【问题描述】:

我正在尝试从 DataTable 中删除一条记录,然后更新它所附加到的数据库。

我删除了我的 DataGridView 的一行,然后使用以下方法更新了我的数据集:

                Me.Tab2_DGVDuty.Rows.RemoveAt(Me.Tab2_DGVDuty.CurrentRow.Index)
                ds1.AcceptChanges()
                Tab2_DGVDuty.Refresh()

然后我调用我的 adapter.update 如下:

            Dim adapter As New SqlDataAdapter
            Dim cmdBuilder As New SqlCommandBuilder(adapter)
            Dim DutyDetails As String = "SELECT * from MyTable"

            adapter.SelectCommand = New SqlCommand(DutyDetails, SQLConn)
            adapter.UpdateCommand = cmdBuilder.GetUpdateCommand
            adapter.DeleteCommand = cmdBuilder.GetDeleteCommand

            Dim cb As SqlCommandBuilder = New SqlCommandBuilder(adapter)

            adapter.Update(ds1.Tables("DT_Table"))

但是当我重新加载数据时,我的记录仍然存在。如果我更改一个值并更新它可以正常工作,但由于某种原因删除不会。

非常感谢任何帮助。

编辑: 好的,我按照以下建议将删除更改为以下内容:

ds1.Tables("DT_Table").Rows(Tab2_DGVDuty.CurrentRow.Index).Delete()

这是附加到一个按钮,它第一次删除很好,但在第二次按下删除另一条记录时没有任何反应。如果我使用

ds1.AcceptChanges()

然后它工作正常。但是,如果我使用上面的代码,那么下面的代码不会从数据库中删除任何内容:

            Dim adapter As New SqlDataAdapter
            Dim cmdBuilder As New SqlCommandBuilder(adapter)
            Dim DutyDetails As String = "SELECT * from MyTable"

            adapter.SelectCommand = New SqlCommand(DutyDetails, SQLConn)
            adapter.UpdateCommand = cmdBuilder.GetUpdateCommand
            adapter.DeleteCommand = cmdBuilder.GetDeleteCommand

            Dim cb As SqlCommandBuilder = New SqlCommandBuilder(adapter)

            adapter.Update(ds1.Tables("DT_Table"))

【问题讨论】:

  • 您需要创建您的数据适配器并将其与数据表或其他东西相关联,例如 da.Fill(dt),然后才能对 da.update 进行任何更改。您不能创建 ds、删除行、创建数据适配器、将其与 ds 关联,然后更新 da 并期望它知道对 ds 的更改。那是你在做什么?

标签: vb.net sql-server-2008 visual-studio-2008


【解决方案1】:
  1. 你不想从DataTable中删除DataRow,你想Delete

    ds1.Tables("DT_Table").Rows(Tab2_DGVDuty.CurrentRow.Index).Delete()
    
  2. 之后不要调用ds1.AcceptChanges(),因为Update 将无法识别该行已更改,因为它会将RowState 更改为UnchangedDataAdapter.Update 调用 AcceptChanges 作为最后一步,而不是你。

  3. 我假设Tab2_DGVDutyDataGridView 而不是DataTable,我在上面已经考虑到了这一点。

【讨论】:

  • 谢谢蒂姆,.Delete 对我不起作用,因为它给了我一个“删除不是成员..”,但删除 Ds1.AcceptChanges 现在可以正确更新 SQL。非常感谢。
  • @user1295053:如果这是您想要的,从数据表中删除的行不会导致执行删除语句。所以你真的应该使用DataRow.Delete。我假设您没有使用我的代码,但是像 Me.Tab2_DGVDuty.Rows.Delete(..) 这样的代码当然不起作用。如果要删除数据库中的DataRow,则必须将其RowState 更改为Deleted,然后使用DataAdapter 更新行、表或DataSet。
  • 我使用了您的确切代码 `Me.Tab2_DGVDuty.Rows(Me.Tab2_DGVDuty.CurrentRow.Index).Delete() 并收到了我所说的错误消息。我在上面的代码中使用的行工作正常,所以不确定你的意思,因为它正在从数据表和数据库中删除。
  • @user1295053:所以我认为Me.Tab2_DGVDutyDataGridView 而不是你提到的DataTable
  • @TimSchmelter +1 我也这么认为。 @user 试试Me.Tab2_DGVDuty.Rows(Me.Tab2_DGVDuty.CurrentRow.Index).Row.Delete()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多