打印

[asp.net教程] datagrid常见解决方案:在分页状态下删除纪录的问题

datagrid常见解决方案:在分页状态下删除纪录的问题

在使用datagrid分页的时候,正常情况下,绑定数据库列表纪录时会自动产生分页的效果,然而我发觉在删除纪录的时候总会发生"无效的 currentpageindex 值。它必须大于等于 0 且小于 pagecount。"的异常,其实解决这个问题很简单,我们要做的就是在datagrid1_deletecommand事件中判断currentpageindex的值,并根据不同的结果来绑定datagrid。
   
  //检索数据库的函数
  public dataset getzcbd()
  {
  try
  {
  dataset ds=new dataset();
  string searchstring="select id,yy,bj from zc";
  da=new oledbdataadapter(searchstring,conn);
  da.fill(ds,"yy");
  return ds;
  }
  catch
  {
  return null;
  }
   
  }
   
  //绑定datagrid
  private void bindgrid()
  {
  dataset ds = new dataset();
  ds = us.getzcbd();
  if (ds!=null)
  {
  this.datagrid1.datasource = ds;
  this.datagrid1.databind();
  }
  else
  {
  msg.alert("加载数据错误!",page);
  }
  }
   
  //删除数据库纪录函数
  public string deletezcbd(int bdid)
  {
   
  int count = this.ifexisezysx(bdid);//不必理会次句,默认count=1
  if (count <= 0) return "false";
  else
  {
  string sqlstr = "delete from zcwhere id="+bdid;
  oledbcommand cmd = new oledbcommand(sqlstr,conn);
   
  conn.open();
   
  try
  {
  cmd.executenonquery();
  return "true";

  }
  catch(exception e)
  {
  return e.message.tostring();
  }
  finally
  {
  conn.close();
  }
  }
  }
   
  // datagrid1_deletecommand事件修改函数
  private void datagrid1_deletecommand(object source, system.web.ui.webcontrols.datagridcommandeventargs e)
  {
  int bdid = int.parse(datagrid1.datakeys[(int)e.item.itemindex].tostring());
  string isdel = us.deletezcbd(bdid);
  int currentpage = 0;
  if (isdel == "true")
  {
  if(this.datagrid1.currentpageindex == this.datagrid1.pagecount -1)
  {
  if (this.datagrid1.currentpageindex == 0)
  {
  this.datagrid1.currentpageindex = this.datagrid1.pagecount -1;
  }
  else
  {
  if (this.datagrid1.items.count % this.datagrid1.pagesize == 1)
  {
  currentpage = 2;
  }
  else
  {
  currentpage = 1;
  }
  this.datagrid1.currentpageindex = this.datagrid1.pagecount - currentpage;
  }
  }
  this.bindgrid();
  }
  else
  {
  msg.alert("删除数据错误!",page);
  }
   
  }
  注释:msg为一个类似winform的messagebox对话框,不必理会。可以使用label.text代替

TOP

返回顶部
AYBlue

Processed in 0.060634 second(s), 7 queries.

当前时区 GMT+8, 现在时间是 2009-1-10 10:59 京ICP备06054220号

清除 Cookies - 联系我们 - 163K.com - Archiver - WAP