您的位置:首页 > 其它

关于GridView翻页checkBox状态保存的问题

2011-03-10 14:27 447 查看
主要功能:

1.实现GridView的分页功能.

2.实现GridView分页时候记录下checkBox的状态

主要代码:

下面代码显示了GridView的使用

<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" AllowPaging="True"
PageSize="5" Width="324px" DataKeyNames="CategoryID"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

请注意这里AllowPaging设置为true,表示启用了分页,而且分页大小为5。DataKeyNames设置为CategoryID,因为他是数据库使用的主键。

使用后台代码,首先定义一个常量

/* QUERY */
private const string QUERY_SELECT_ALL_CATEGORIES = "SELECT * FROM Categories";

这个常量在BindData里使用用来获取数据源

private void BindData()
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(QUERY_SELECT_ALL_CATEGORIES,
myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
GridView1.DataSource = ds;
GridView1.DataBind();
}

保存CheckBox的值

GridView在分页过程中并不维护CheckBox的选择状态,幸运的是,我们可以使用Session来维护CheckBox的状态,这个功能使用RememberOldValues完成

private void RememberOldValues()
{
ArrayList categoryIDList = new ArrayList();
int index = -1;
foreach (GridViewRow row in GridView1.Rows)
{
index = (int) GridView1.DataKeys[row.RowIndex].Value;
bool result = ((CheckBox)row.FindControl("CheckBox1")).Checked;

// Check in the Session
if (Session[CHECKED_ITEMS] != null)
categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (result)
{
if (!categoryIDList.Contains(index))
categoryIDList.Add(index);
}
else
categoryIDList.Remove(index);
}
if (categoryIDList != null && categoryIDList.Count > 0)
Session[CHECKED_ITEMS] = categoryIDList;
}

还原CheckBox的状态

下一步,需要定义一个方法来还原Checkbox的状态值

private void RePopulateValues()
{
ArrayList categoryIDList = (ArrayList)Session[CHECKED_ITEMS];
if (categoryIDList != null && categoryIDList.Count > 0)
{
foreach (GridViewRow row in GridView1.Rows)
{
int index = (int)GridView1.DataKeys[row.RowIndex].Value;
if (categoryIDList.Contains(index))
{
CheckBox myCheckBox = (CheckBox) row.FindControl("CheckBox1");
myCheckBox.Checked = true;
}
}
}
}

最后,在分页事件里调用上面两个方法

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
GridView1.PageIndex = e.NewPageIndex;
BindData();
RePopulateValues();
}

注意的问题:

1.在GridView中必须设置 DataKeyNames = "数据表的主键"

2.设置CheckBox ID="checkbox1" 的属性(根据后台需要进行更改)

3.Session[CHECKED_ITEMS] 为页面的checkbox列,要加双引号 Session["CHECKED_ITEMS"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: