Gridview小技巧-保存選擇狀態

本文介绍如何在ASP.NET的GridView控件中实现分页加载数据,并保持CheckBox的选择状态。通过使用ViewState来保存每页中被选中的项的状态,确保在页面跳转时能够正确恢复这些状态。

gridview 缺省的分頁是一次性載入所有數據,對大一點的項目肯定是不行的,所以大家都會用其它的分頁控件一頁一頁載入數據.

做批量操作時通常會有一個"CheckBox"列,但如果翻頁就需要保存選擇的狀態,用viewstate來保存還是比較簡單的.

下面代碼放到分頁改變事件中用來把選擇ID列表保存到viewstate中.

ContractedBlock.gifExpandedBlockStart.gifCode
    
    
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {

        
#region save select status

        List
<string> IDList = new List<string>();

        
if (ViewState["IDList"!= null)
            IDList 
= (List<string>)ViewState["IDList"];

        
int i = 0;

        
for (i = 0; i < gvData.Rows.Count; i++)
        {
            
string ID = gvData.DataKeys[i].Value.ToString();

            
if (((CheckBox)gvData.Rows[i].FindControl("select")).Checked)
            {                
                
if (!IDList.Contains(ID))
                    IDList.Add(ID);
            }
            
else
            {
                
if (IDList.Contains(ID))
                    IDList.Remove(ID);

            }
        }

        ViewState[
"IDList"= IDList;

        
#endregion

        
//做分頁的其他事情.
    }

 

下面的代碼,gridview在邦定數據時根據viewstate決定是否選擇.

 

ContractedBlock.gifExpandedBlockStart.gifCode
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            
#region get the select status and decide the checbox select status

            List
<string> IDList = new List<string>();
            
if (ViewState["IDList"]!=null)
                IDList 
= (List<string>)ViewState["IDList"];

            
string ID = gvData.DataKeys[e.Row.RowIndex].Value.ToString();

            CheckBox cb 
= (CheckBox)e.Row.Cells[0].FindControl("select");
            
if (IDList.Contains(ID))
            {
                cb.Checked 
= true;
            }
            
else
            {
                cb.Checked 
= false;
            }

            
#endregion

        }

 


    //使用的時候也一樣,從viewstate中讀出ID列表
            List<string> IDList = new List<string>();
            if (ViewState["IDList"]!=null)
                IDList = (List<string>)ViewState["IDList"];

转载于:https://www.cnblogs.com/wangxiaohuo/archive/2008/09/19/1293962.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值