在DataGrid中持久化跨页面的选中状态






4.21/5 (12投票s)
2005年9月4日
2分钟阅读

76448

715
本文介绍如何在 DataGrid 中持久化选中状态跨页面。
引言
之前我写过一篇文章,介绍了如何在网格中添加复选框以选择记录。现在我回来了,对该文章进行了一些增强,以便在分页之间保持选中状态。对于直接阅读本文的人,我建议他们先阅读上述文章,然后再回来。
问题陈述
我们可以将问题描述如下:
用户在一个页面中选中一条记录,然后转到下一页并选择一些记录,当他返回到上一页时,我们需要保持他之前选中记录的选中状态。我将称之为跨页面的选中状态维护。当他完成所有页面的检查后,他需要一个他已检查记录的列表。
我们的方法
我实现此功能的方法是将选中记录的 ID 保存在一个隐藏的 ListBox
中。在网格的 ItemDataBound
事件中,我检查记录的 ID 是否存在于 ListBox
中,并设置记录的选中状态。
步骤 1:保存选中的记录
在 Page_Load
中,我正在调用一个私有函数 MaintainState()
。
我遍历所有 DataGrid
项目,并检查复选框是否被选中。如果被选中,我会将其添加到 ListBox
中,前提是它不在其中。如果复选框未被选中,并且它在 ListBox
中,我会将其删除。
以下是该函数的实现:
private void MaintainState()
{
//state maintaining
foreach( DataGridItem di in myDataGrid.Items )
{
HtmlInputCheckBox chkBx = (HtmlInputCheckBox)di.FindControl("EmpId") ;
//if check box is checked add it
if( chkBx !=null && chkBx.Checked )
{
Label lbl = (Label)di.FindControl("Id");
ListItem item=new ListItem(lbl.Text ,lbl.Text );
if(!SelectedList.Items.Contains(item))
{
SelectedList.Items.Add(item );
}
}
//if check box is not checked then
if(( chkBx !=null )&& !(chkBx.Checked) )
{
Label lbl = (Label)di.FindControl("Id");
ListItem item=new ListItem(lbl.Text ,lbl.Text );
//if un checked item is in the list then remove
if(SelectedList.Items.Contains(item))
{
SelectedList.Items.Remove(item );
}
}
}
//end of state maintaining
}
步骤 2:返回时设置选中状态
现在我们已经在隐藏的 ListBox
中有了选中的记录,我们需要在数据再次绑定时(跨页面)设置复选框的选中状态。我们将在网格的 ItemDataBound
事件中编写此代码,即数据正在绑定到网格时。我们将绑定每个项目时进行检查。如果它是 Item
或 AlternatingItem
,则获取记录的 ID,检查 ID 是否在 ListBox
中,并设置选中状态。
实现如下:
private void myDataGrid_ItemDataBound(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
//check and uncheck based on the item entry in the List
if((e.Item.ItemType== ListItemType.Item )||
(e.Item.ItemType== ListItemType.AlternatingItem ))
{
HtmlInputCheckBox chkBx =
(HtmlInputCheckBox)e.Item.Cells[0].FindControl("EmpId");
Label lbl = (Label)e.Item.Cells[1].FindControl("Id");
ListItem item = new ListItem(lbl.Text , lbl.Text );
if(SelectedList.Items.Contains (item))
chkBx.Checked =true;
else
chkBx.Checked=false;
}
}
有一点需要记住,就是在完成操作后清除 ListBox
;)。