DataGrid常見解決方案:在分頁狀態下刪除紀錄的問題
2024-07-21 02:23:39
供稿:網友
在使用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代替