日期:2012-08-24 浏览次数:20909 次
当把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