• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
拿一份干净工资,过一个简单生活
c#——最优雅的语言
博客园    首页    新随笔    联系   管理    订阅  订阅
Gridview小技巧-保存選擇狀態

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

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

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

Code
    
    
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決定是否選擇.

 

Code
        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"];

posted on 2008-09-19 11:16  老头  阅读(640)  评论(2)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3