ASP.NET GirdView学习之六 使用模板列实现多行删除2011-12-18 cnblogs mdy41034264
1using System;
 2using System.Data;
 3using System.Configuration;
 4using System.Collections;
 5using System.Web;
 6using System.Web.Security;
 7using System.Web.UI;
 8using System.Web.UI.WebControls;
 9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11using System.Collections.Generic;
12
13public partial class GridViewTemplateTest : System.Web.UI.Page
14{
15//当前页码,从0开始
16private int curPage
17{
18get
19{
20return ViewState["curPage"] == null ? 0 : Convert.ToInt32(ViewState["curPage"]);
21}
22set
23{
24ViewState["curPage"] = value;
25}
26}
27protected void Page_Load(object sender, EventArgs e)
28{
29if (!IsPostBack)
30{
31ClientInfoAccessObj accessor = new ClientInfoAccessObj();
32curPage = 0;//显示第一页33GridView1.DataSource = accessor.GetAllClients();
34GridView1.DataBind();
35}
36}
37protected void btnDeleteSelectedInfo_Click(object sender, EventArgs e)
38{
39List<int> SelectedClientIDs = GetSelectedClientIDs();
40if (SelectedClientIDs.Count == 0)
41return;
42
43ClientInfoAccessObj accessor = new ClientInfoAccessObj();
44foreach (int id in SelectedClientIDs)
45{
46accessor.DeleteClientInfoForID(id);
47}
48ClientScript.RegisterStartupScript(this.GetType(), "info", "alert("记录已成功删除");", true);
49
50//计算应该显示哪一页
51if (SelectedClientIDs.Count == GridView1.PageSize) //选中全页上的所有记录
52if (curPage != 0)
53curPage--; //显示前一页
54
55
56//重新绑定数据并显示
57GridView1.DataSource = accessor.GetAllClients();
58GridView1.PageIndex = curPage;
59GridView1.DataBind();
60}
61
62private List<int> GetSelectedClientIDs()
63{
64List<int> ids = new List<int>();
65//循环查找被选中的行
66foreach (GridViewRow gvr in GridView1.Rows)67{
68//是数据行
69if (gvr.RowType == DataControlRowType.DataRow)
70{
71//根据模板列中的控件ID查找指定的控件
72CheckBox chk = gvr.FindControl("CheckBox1") as CheckBox;
73if ((chk != null) && chk.Checked)
74//取出选中行的主键,加入到集合中
75ids.Add((int)GridView1.DataKeys[gvr.RowIndex].Value);
76}
77}
78return ids;
79}
80protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
81{
82ClientInfoAccessObj accessor = new ClientInfoAccessObj();
83GridView1.DataSource = accessor.GetAllClients();
84GridView1.PageIndex = e.NewPageIndex;
85GridView1.DataBind();
86//保存当前页码
87curPage = e.NewPageIndex;
88}
89}
90