最近用.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();
}