gridview 缺省的分頁是一次性載入所有數據,對大一點的項目肯定是不行的,所以大家都會用其它的分頁控件一頁一頁載入數據.
做批量操作時通常會有一個"CheckBox"列,但如果翻頁就需要保存選擇的狀態,用viewstate來保存還是比較簡單的.
下面代碼放到分頁改變事件中用來把選擇ID列表保存到viewstate中.
Code
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
#region save select status
List<string> IDList = new List<string>();
if (ViewState["IDList"] != null)
IDList = (List<string>)ViewState["IDList"];
int i = 0;
for (i = 0; i < gvData.Rows.Count; i++)
{
string ID = gvData.DataKeys[i].Value.ToString();
if (((CheckBox)gvData.Rows[i].FindControl("select")).Checked)
{
if (!IDList.Contains(ID))
IDList.Add(ID);
}
else
{
if (IDList.Contains(ID))
IDList.Remove(ID);
}
}
ViewState["IDList"] = IDList;
#endregion
//做分頁的其他事情.
}
下面的代碼,gridview在邦定數據時根據viewstate決定是否選擇.
Code
if (e.Row.RowType == DataControlRowType.DataRow)
{
#region get the select status and decide the checbox select status
List<string> IDList = new List<string>();
if (ViewState["IDList"]!=null)
IDList = (List<string>)ViewState["IDList"];
string ID = gvData.DataKeys[e.Row.RowIndex].Value.ToString();
CheckBox cb = (CheckBox)e.Row.Cells[0].FindControl("select");
if (IDList.Contains(ID))
{
cb.Checked = true;
}
else
{
cb.Checked = false;
}
#endregion
}
//使用的時候也一樣,從viewstate中讀出ID列表
List<string> IDList = new List<string>();
if (ViewState["IDList"]!=null)
IDList = (List<string>)ViewState["IDList"];