DataGrid在分頁狀態(tài)下刪除紀(jì)錄的問題
2024-07-21 02:17:11
供稿:網(wǎng)友
在使用datagrid分頁的時(shí)候,正常情況下,綁定數(shù)據(jù)庫列表紀(jì)錄時(shí)會(huì)自動(dòng)產(chǎn)生分頁的效果,然而我發(fā)覺在刪除紀(jì)錄的時(shí)候總會(huì)發(fā)生"無效的 currentpageindex 值。它必須大于等于 0 且小于 pagecount。"的異常,其實(shí)解決這個(gè)問題很簡單,我們要做的就是在datagrid1_deletecommand事件中判斷currentpageindex的值,并根據(jù)不同的結(jié)果來綁定datagrid。
//檢索數(shù)據(jù)庫的函數(shù)
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("加載數(shù)據(jù)錯(cuò)誤!",page);
}
}
//刪除數(shù)據(jù)庫紀(jì)錄函數(shù)
public string deletezcbd(int bdid)
{
int count = this.ifexisezysx(bdid);//不必理會(huì)次句,默認(rèn)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事件修改函數(shù)
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("刪除數(shù)據(jù)錯(cuò)誤!",page);
}
}
注釋:msg為一個(gè)類似winform的messagebox對話框,不必理會(huì)。可以使用label.text代替
代碼很亂,敬請諒解!