在使用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代替
代码很乱,敬请谅解!