當把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()
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)