完整後台程式碼
public partial class GridViewTemplateTest : System.Web.UI.Page
{
private int curPage
{
get { return ViewState["curPage"] == null ? 0 : Convert.ToInt32(ViewState["curPage"]); }
set { ViewState["curPage"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
curPage = 0;
GridView1.DataSource = new ClientInfoAccessObj().GetAllClients();
GridView1.DataBind();
}
}
protected void btnDeleteSelectedInfo_Click(object sender, EventArgs e)
{
List<int> ids = GetSelectedClientIDs();
if (ids.Count == 0) return;
var accessor = new ClientInfoAccessObj();
foreach (int id in ids) accessor.DeleteClientInfoForID(id);
ClientScript.RegisterStartupScript(this.GetType(), "info", "alert('記錄已成功刪除');", true);
// 若刪除整頁資料且非第一頁,回上一頁
if (ids.Count == GridView1.PageSize && curPage != 0) curPage--;
GridView1.DataSource = accessor.GetAllClients();
GridView1.PageIndex = curPage;
GridView1.DataBind();
}
private List<int> GetSelectedClientIDs()
{
var ids = new List<int>();
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = row.FindControl("CheckBox1") as CheckBox;
if (chk != null && chk.Checked)
ids.Add((int)GridView1.DataKeys[row.RowIndex].Value);
}
}
return ids;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = new ClientInfoAccessObj().GetAllClients();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
curPage = e.NewPageIndex;
}
}
關鍵技巧
- 使用
TemplateField 放置 CheckBox 實現多選。
DataKeys 取得主鍵值,避免顯示於畫面。
- 刪除後智慧調整
PageIndex,防止頁面空白。