當把DataSet 綁定到Datagrid控件,
並利用DataAdapter對象修改數據庫
如:
dim adp as new OleDbDataAdapter(stradp,conn)
dim ocb as new OleDbCommandBuilder(adp)
adp.DeleteCommand = ocb.GetDeleteCommand()
adp.Update(ds,"Orders")
--------------------------------
執行刪除操作時,如我們加入這樣一個方法:
sub mydatagrid_delete(sender as object, e as datagridcommandeventargs)
dim dt as new DataTable()
dt = ds.Tables("Orders")
dim dr as DataRow
dr = dt.Rows(E.Item.ItemIndex)
dr.delete
'dr.AcceptChanges '曾經嘗試使用徹底刪除,發現adp自動更新回數據庫時,無法自動生成相應的sql語句
'解決刪除當前頁最後一項時出現的頁索引異常
' *****************************************************************
dim lastEditPage as integer = mydatagrid.currentPageIndex
If (mydatagrid.pageCount - mydatagrid.currentPageIndex) = 1 and mydatagrid.Items.Count = 1 Then
If mydatagrid.pageCount > 1 Then
lastEditPage = LastEditPage - 1
Else
lastEditPage = 0
End If
End If
mydatagrid.currentPageIndex = lastEditPage
' ****************************************************************
session("orderList") = ds
mydatagrid.edititemindex = -1
mydatagrid.datasource = ds.tables("Orders")
mydatagrid.databind()
end sub
當由第一個開始逐個刪除時出現了異常,發現在刪除第二時,刪不掉,即原來的dr(2)沒有自動變為dr(1)。如果我們使用dr.delete dr.acceptChanges則可以自動變化,但是上面說明了,則無法使用自動更新回到數據庫。我們必須獲得刪除時的實際索引,所以就用了一個本方法,在當前的ds中另外建了一個Table,保持同步刪除,但是在Table的id列中,保存實際的索引值,具體代碼如下:
解決dr索引的一個辦法:
dim orderTable as new DataTable() '建一個臨時表用來保存索引,保持同步刪除
dim theNewRow as DataRow
dim dc as DataColumn
orderTable.TableName = "orderId"
ds.Tables.add(orderTable)
dc = new DataColumn()
dc.ColumnName = "id"
orderTable.columns.add(dc)
dim dcKey() as DataColumn = {orderTable.Columns("id")}
orderTable.primaryKey = dcKey
dim i as integer
For i = 0 to (ds.Tables("Users").Rows.Count - 1)
theNewRow = orderTable.NewRow() &nb
sp;
theNewRow("id") = i.toString()
orderTable.Rows.add(theNewRow)
Next
上述刪除功能中加的代碼,替換 dr = dt.Rows(e.Item.ItemIndex):
dim drOrder as DataRow
drOrder = ds.Tables("orderId").Rows(E.Item.ItemIndex)
dim currentOrder as integer = CInt(drOrder("id")) + mydatagrid.currentPageIndex * mydatagrid.PageSize
dr = dt.Rows(currentOrder)
drOrder.delete
如果有更新功能,則替換dr = dt.Rows(e.Item.ItemIndex):
dim drOrder as DataRow
drOrder = ds.Tables("orderId").Rows(E.Item.ItemIndex)
dim currentOrder as integer = CInt(drOrder("id")) + mydatagrid.currentPageIndex * mydatagrid.PageSize
dr = dt.Rows(currentOrder)