您的位置:首页 > 编程语言 > ASP

Asp.net 实现GridView分页时记录CheckBox状态

2011-08-08 16:51 495 查看
用GridView自带的方法实现分页功能。

用ViewState记录GridView分页后各个分页面的CheckBox的选中状态。

GridView不同分页面之间的跳转只是刷新当前页面,并没有跳出当前Web页面的生命周期。(这也是ViewState的作用范围)

如果想要在不同Web页面之间跳转实现信息传递的话,可以用Cookie,Session等。

当我们写Asp.net程序的时候避免不了的是从数据库中取数据,然后将这些数据显示在页面上,当数据非常多的时候我们又很自然的想到了把这些数据进行分页显示。分页在Asp.net中用到的地方是非常多的,我们可以自己去编写分页程序,也可以用Asp.net给我们封装好的。这里我们用Asp.net封装好的分页功能,并用ViewState实现实现不同分页面的CheckBox的状态:

用GridView去显示数据的时候避免不了的与CheckBox的结合(即:将GridView的每一行的第一列设置为CheckBox)方法如下:可以用拖控件的方法去创建GridView然后在GridView控件中加入CheckBox列。body的代码如下:其中onpageindexchanging="GridView1_PageIndexChanging"表示选择不同分页面时所调用的方法,AllowPaging="True"表示此GridView允许自带的分页,PageSize=“5”表示每页的行数为5(可以在GridView1的属性中去选择填写)

<body style="height: 12px; width: 688px">
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" Height="289px" Width="673px"
onpageindexchanging="GridView1_PageIndexChanging" AllowPaging="True" PageSize="5">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" Checked =false AutoPostBack =true runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" />
</asp:GridView>
</div>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="SelectAll" />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="CancelAll" />

</form>
</body>

页面布局时注意:若用拖控件和写代码混合生成界面时,一定要保证...aspx.designer.cs中有所有控件的注册信息(这也是为什么许多从网上复制的代码拷贝到自己的工程当中出错的原因之一,初学者很容易犯这样的错误)。如:上面GridView,CheckBox,Button1, Button2的注册信息为:

protected global::System.Web.UI.WebControls.GridView GridView1;
protected global::System.Web.UI.WebControls.CheckBox CheckBox1;
protected global::System.Web.UI.WebControls.Button Button1;
protected global::System.Web.UI.WebControls.Button Button2;

用GridView分页去显示数据的时候有一个弊端:GridView只能记录当前页面所显示的数据,而不去保存其他页面的控件状态,比如:我在第一页上选择了1行(在CheckBox上打个对号),当我们跳到下一页之后再返回时,选中的那行又恢复到了一开始的状态(没选中)。

想要解决这个问题也有很多方法,比如Session,Cookie等。这里我选择用ViewState变量去记录所有分页面CheckBox的状态(【注】ViewState的作用是:变量可以在跨分页面情况下保存其原来的值,也就是说:其变量所保存的值不会因为我们分页面的跳转而发生改变,但如果是不同的Web页面之间的跳转的话,ViewState就无能为力了,但是我们可以换用Session和Cookie实现)

我们定义一个Pagination类,类中的方法实现CheckBox具体的状态。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FenYe
{
public class Pagination
{
//Remember the station of every CheckBox in all pages
public void RememberOldValues(Dictionary<string, bool> dic, GridView gdv)
{
for (int i = 0; i < gdv.Rows.Count; i++)
{
string currentValue = gdv.Rows[i].Cells[1].Text.Trim();
CheckBox currentCbx = gdv.Rows[i].Cells[0].FindControl("CheckBox1") as CheckBox;
if (currentCbx.Checked && dic[currentValue] == false)
{
dic[currentValue] = true;
}
else if (!currentCbx.Checked && dic[currentValue] == true)
{
dic[currentValue] = false;
}
}
}

//Repopulate the station of every CheckBox in all pages
public void RePopulateValues(Dictionary<string, bool> dic, GridView gdv)
{
foreach (GridViewRow row in gdv.Rows)
{
string currentValue = row.Cells[1].Text.Trim();
CheckBox currentCbx = row.Cells[0].FindControl("CheckBox1") as CheckBox;
if (dic[currentValue] == true)
{
currentCbx.Checked = true;
}
else
{
currentCbx.Checked = false;
}
}
}

//Select all CheckBoxes in all pages
public void SelectAll(Dictionary<string, bool> dic)
{
string[] keys = dic.Keys.ToArray();
dic.Clear();
foreach (string key in keys)
{
dic.Add(key, true);
}
}

//UnSelect all CheckBoxes in all pages
public void UnSelectAll(Dictionary<string, bool> dic)
{
string[] keys = dic.Keys.ToArray();
dic.Clear();
foreach (string key in keys)
{
dic.Add(key, false);
}
}
}
}

假设我们用赋值的方式模拟从数据中读取数据,生成DataTable,然后将此DataTable绑定到GridView数据源中实现分页显示。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace FenYe
{
public partial class _Default : System.Web.UI.Page
{
//声明一个Pagination的类实例(调用其方法实现分页)
Pagination mPage = new Pagination();

//声明一个Dictionary(并将其表明为ViewState属性),
//其中Key值(string)代表User的ID(数据库中的主键),Value值(bool)表示该行的CheckBox是否选中
Dictionary<string, bool> usersDic
{
get
{
return (ViewState["usersdic"]!= null)?(Dictionary<string, bool>)ViewState["usersdic"]:null;
}
set
{
ViewState["usersdic"] = value;
}
}

//声明一个DataTable(并将其标明为ViewState属性),
//去记录User的所有信息,第一列填充的是UserID(数据库中的主键)
DataTable mUsersDT
{
get
{
return (ViewState["usersdt"] != null) ? (DataTable)(ViewState["usersdt"]) : null;
}
set
{
ViewState["usersdt"] = value;
}
}

protected void Page_Load(object sender, EventArgs e)
{
//如果是第一次加载,则走if中的内容
if (!Page.IsPostBack)
{
mUsersDT = GetUsersTable();
FillUsersTable(mUsersDT);
usersDic = InitializeUsersDic(mUsersDT);
//GridView绑定数据源(DataTable)
GridView1.DataSource = mUsersDT;
GridView1.DataBind();
}
}

//当点击GridView不同的分页时,调用如下方法(这个方法需先注册:请看第一部分body的代码)
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//记录原来分页面的所有CheckBox的状态
mPage.RememberOldValues(usersDic, GridView1);
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = mUsersDT;
GridView1.DataBind();
//重构当前选中页面的CheckBox的状态
mPage.RePopulateValues(usersDic, GridView1);
}

//获得UsersTable(初始化DataTable的列属性ID和Name)
protected DataTable GetUsersTable()
{
DataTable dt = new DataTable();
string[] columns = { "ID", "Name"};
foreach (string name in columns)
{
DataColumn column = dt.Columns.Add();
column.ColumnName = name;
}
return dt;
}
//填充User的DataTable的内容
protected void FillUsersTable(DataTable dt)
{
for (int i = 0; i < 20; i++)
{
DataRow row = dt.NewRow();
row["ID"] = i.ToString();
row["Name"] = "Name" + i.ToString();
dt.Rows.Add(row);
}
}

//初始化Dictionary
protected Dictionary<string, bool> InitializeUsersDic(DataTable dt)
{
Dictionary<string, bool> currentDic = new Dictionary<string, bool>();
//将DataTable中的每一行的第一列内容存储到Dictionary中
for (int i = 0; i < dt.Rows.Count; i++)
{
currentDic.Add(dt.Rows[i].ItemArray[0].ToString(), false);
}
return currentDic;
}

//处理Button1的点击事件(选中所有)
protected void Button1_Click(object sender, EventArgs e)
{
mPage.SelectAll(usersDic);
mPage.RePopulateValues(usersDic, GridView1);
}

//处理Button2的点击事件(不选中所有)
protected void Button2_Click(object sender, EventArgs e)
{
mPage.UnSelectAll(usersDic);
mPage.RePopulateValues(usersDic, GridView1);
}
}
}

如果想实现不同Web页面之间数据信息的传递,将上面的代码中ViewState字样换成Session即可,那么在其他页面就可以根据Session["Name"]中的Name进行区别获取Session信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: