从数据集和 sql server 中删除记录 [英] Deleting a record from dataset and sql server
问题描述
我正在尝试从 DataTable 中删除一条记录,然后更新它所附加到的数据库.
I am trying to delete a record from a DataTable and then update the database that it is attached to.
我删除了一行 DataGridView,然后使用以下方法更新我的数据集:
I delete a row of my DataGridView and then update my Dataset using:
Me.Tab2_DGVDuty.Rows.RemoveAt(Me.Tab2_DGVDuty.CurrentRow.Index)
ds1.AcceptChanges()
Tab2_DGVDuty.Refresh()
然后我调用我的adapter.update 如下:
I then call my adapter.update as below:
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"))
但是当我重新加载数据时,我的记录仍然存在.如果我更改一个值并更新,这可以正常工作,但由于某种原因删除不会.
But when i reload the data my record is still there. If I change a value and update this works fine but for some reason the delete doesnt.
非常感谢任何帮助.
好的,我按照以下建议将我的删除更改为以下内容:
OK I changed my delete to the following as suggested below:
ds1.Tables("DT_Table").Rows(Tab2_DGVDuty.CurrentRow.Index).Delete()
这是附加到一个按钮,它第一次删除正常,但在第二次按下删除另一条记录时没有任何反应.如果我使用
This is attached to a button, it deletes fine the first time but on the second press to delete another record nothing happens. If I use
ds1.AcceptChanges()
然后它工作正常.但是,如果我使用上面的代码,那么下面的代码不会从数据库中删除任何内容:
then it works fine. However, if i use the above then my code below does not delete anything from the database:
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"))
推荐答案
您不想从
DataTable
中删除DataRow
,而是希望删除
它
You don't want to remove the
DataRow
from theDataTable
, you want toDelete
it
ds1.Tables("DT_Table").Rows(Tab2_DGVDuty.CurrentRow.Index).Delete()
之后不要调用 ds1.AcceptChanges()
,因为 Update
将无法识别该行已更改,因为它将更改它的 RowState
到 Unchanged
.DataAdapter.Update
隐式调用 AcceptChanges
作为最后一步,而不是你.
Don't call ds1.AcceptChanges()
afterwards since the Update
will not recognize that this row has changed anymore then because it will change it's RowState
to Unchanged
. DataAdapter.Update
calls AcceptChanges
as the last step implicitely, not you.
我假设 Tab2_DGVDuty
是一个 DataGridView
而不是 DataTable
,我在上面已经考虑到了这一点.p>
I assume that Tab2_DGVDuty
is a DataGridView
and not the DataTable
, i've taken that into account above.
这篇关于从数据集和 sql server 中删除记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!