换页时,Gridview当前页选中的CheckBox选中状态不会丢失

来源:互联网 发布:淘宝客增加权重吗 编辑:程序博客网 时间:2024/06/09 17:47

    客户端代码:

function check(opt,id)
{
    var chk = window.document.getElementById(opt);
    if(chk.checked == true)
    {
        chk.checked = false;
    }
    else
    {
        chk.checked = true;
    }
    var ids = window.document.getElementById("TextBox1");
    var s = ids.value;
    s = s.replace("|"+id+";","");
    if(chk.checked)
    {
     s += "|"+id+";";
    }
    ids.value = s;
}

    服务器端代码:

    private ArrayList arrRole = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        string ids = this.TextBox1.Text.Trim();
        if (ids != "")
        {
            string[] roles = ids.Split('|');
            for (int i = 1; i < roles.Length; i++)
            {
                this.arrRole.Add(roles[i].Substring(0, roles[i].Length - 1));
            }
        }
        #region 为Gridview1绑定数据
        DataSet ds = new DataSet();
        ds.ReadXml(this.MapPath("example.xml"));
        this.GridView1.DataSource = ds.Tables[0];
        this.GridView1.DataBind();
        #endregion
        foreach (GridViewRow row in this.GridView1.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
            chk.Checked = this.arrRole.Contains(row.Cells[2].Text.Trim());
        }
    }

服务器端定义方法:

 protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Pager)
        {
            return;
        }
        e.Row.Cells[0].Attributes.Add("style", "display: none;");
        if (e.Row.RowType == DataControlRowType.DataRow)//点击Gridview行,选中/取消选中,当前行中的Checkbox
        {
            //e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='Red';this.style.cursor = 'hand';");
            //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor = c;");
            CheckBox ch = ((CheckBox)e.Row.FindControl("CheckBox1"));
            ch.Attributes.Add("onclick", "check('" + e.Row.FindControl("CheckBox1").ClientID.Replace("_", "$") + "','"+e.Row.Cells[2].Text.Trim()+"')");
            e.Row.Attributes.Add("onclick", "check('" + e.Row.FindControl("CheckBox1").ClientID.Replace("_", "$") + "','" + e.Row.Cells[2].Text.Trim() + "')");
        }
    }