WEB开发网
开发学院WEB开发ASP.NET datagrid与DataSet结合使用中出现的索引问题 阅读

datagrid与DataSet结合使用中出现的索引问题

 2005-05-23 17:01:55 来源:WEB开发网   
核心提示:当把DataSet 绑定到Datagrid控件,并利用DataAdapter对象修改数据库 如: dim adp as new OleDbDataAdapter(stradp,conn) dim ocb as new OleDbCommandBuilder(adp) adp.DeleteCommand = ocb.Ge

当把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)

Tags:datagrid DataSet 结合

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接