zoukankan      html  css  js  c++  java
  • 转:GridView翻页时保存模板列内的RadioButtonList选择状态

    最近用.NET做一个项目时,发现GridView翻页时,模板列内的RadioButtonList所选择的项不能保存。在网上搜了一下解决方法,发现大都是模板列内是Checkbox的,RadioButtonList的很少。其实这两个的原理是一样的,要解决这个问题,核心就是写两个方法,分别是保存状态和还原状态,然后在GridView的翻页事件(GridView1_PageIndexChanging)里分别调用这两个方法。代码如下:

    //保存RadioButtonList选择的项
    protected void Save()
    {       
            Hashtable ht = new Hashtable();           //实例化一个Hashtable,用于储存RadioButtonList选中的值。

            for (int i = 0; i < this.GridView1.Rows.Count; i++)    //循环GridView每一行
            {
                int id = Convert.ToInt32(this.GridView1.DataKeys[i].Value.ToString());   //获取GridView每一行对应的id
                RadioButtonList rbtn = (RadioButtonList)this.GridView1.Rows[i].FindControl("rbtnMatter");
                int matter = Convert.ToInt32(rbtn.SelectedValue);   

                if (ViewState["ht"] != null)
                {
                    ht = (Hashtable)ViewState["ht"];
                    if (ht.Contains(id))
                    {
                        ht.Remove(id);
                    }           
                }         
                ht.Add(id, matter);
                ViewState["ht"] = ht;
            }
    }

    //还原RadioButtonList选择的项
        protected void Revert()
        {
            Hashtable ht = (Hashtable)ViewState["ht"];
            for (int i = 0; i < this.GridView1.Rows.Count; i++)
            {
                int id = Convert.ToInt32(this.GridView1.DataKeys[i].Value.ToString());
                if (ht.Contains(id))
                {
                    int matter = (int)ht[id];
                    RadioButtonList rbtn = (RadioButtonList)this.GridView1.Rows[i].FindControl("rbtnMatter");
                    rbtn.SelectedIndex = matter;
                }
            }
        }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
            Save();
            this.GridView1.PageIndex = e.NewPageIndex;
            GridViewBind();
            Revert();
    }

    魔兽就是毒瘤,大家千万不要玩。
  • 相关阅读:
    tomcat启动脚本
    libcrypto.so.1.0.0内容丢失导致sshd无法运行解决方案
    linux最小安装
    linux下文件删除的原理
    Web服务器磁盘满故障深入解析
    入驻博客园,新的开始!!!
    其实我们都可以变得更加优秀!
    我的未来在哪里呢!
    学会选择
    SpringBoot+vue.js如何通过post方式实现导出excel
  • 原文地址:https://www.cnblogs.com/tracy/p/1764925.html
Copyright © 2011-2022 走看看