明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

DataGrid經(jīng)常見處理方案:在分頁(yè)狀態(tài)下刪除紀(jì)錄的問題

[摘要]在使用DataGrid分頁(yè)的時(shí)候,正常情況下,綁定數(shù)據(jù)庫(kù)列表紀(jì)錄時(shí)會(huì)自動(dòng)產(chǎn)生分頁(yè)的效果,然而我發(fā)覺在刪除紀(jì)錄的時(shí)候總會(huì)發(fā)生"無(wú)效的 CurrentPageIndex 值。它必須大于等于 0...
在使用DataGrid分頁(yè)的時(shí)候,正常情況下,綁定數(shù)據(jù)庫(kù)列表紀(jì)錄時(shí)會(huì)自動(dòng)產(chǎn)生分頁(yè)的效果,然而我發(fā)覺在刪除紀(jì)錄的時(shí)候總會(huì)發(fā)生"無(wú)效的 CurrentPageIndex 值。它必須大于等于 0 且小于 PageCount。"的異常,其實(shí)解決這個(gè)問題很簡(jiǎn)單,我們要做的就是在DataGrid1_DeleteCommand事件中判斷CurrentPageIndex的值,并根據(jù)不同的結(jié)果來(lái)綁定DataGrid。

//檢索數(shù)據(jù)庫(kù)的函數(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ù)庫(kù)紀(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對(duì)話框,不必理會(huì)。可以使用label.Text代替