首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET GridView 進階教學(六):TemplateField 實現多列勾選刪除與分頁狀態保持

     編輯:關於ASP.NET

完整後台程式碼

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,防止頁面空白。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved