在分页和循环遍历整个GridView时,请记住GridView中的复选框选项

时间:2014-04-14 06:14:37

标签: c# asp.net gridview pagination

我在gridview页面上有一个aspx并启用了分页功能。此gridview包含数据库中的一些数据字段和每行check-box

COD Pagination

现在,我读了这篇文章:loop all gridview rows on button click when paging enabled为了能够遍历gridview所有页面上的所有行,我必须禁用分页,重新绑定{{1循环遍历所有行,重新启用分页,最后重新绑定gridview。

我开始想知道如果在循环遍历所有行之前重新绑定gridview,是否会记住复选框选项,但很快就确定即使从一个页面转到下一个页面然后再返回{ {1}}选项丢失。

我需要在每行上添加datasource分页和check-box,然后在点击按钮时循环遍历整个gridview并根据{执行一些操作{1}}选项。

1 个答案:

答案 0 :(得分:1)

本机无法使用GridView。但是有很多方法可以模拟相同的行为。一种方法是像这样处理PageIndexChanging事件的问题。

protected void OriginalTable_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    var selectedIDs = (Session["CheckedIDs"] != null) ? 
        Session["CheckedIDs"] as List<int> : new List<int>();

    //we are now at current page. set the checked ids to a list
    foreach (GridViewRow row in OriginalTable.Rows)
    {
        //get the checkbox in the row ( "HasEmail" is the name of the asp:CheckBox )
        var emailCheckBox = row.FindControl("HasEmail") as CheckBox;
        //gets the primary key of the corresponding row
        var rowOrgID = Convert.ToInt32(OriginalTable.DataKeys[row.RowIndex].Value);
        //is row org_id in the selectedIDs list
        var isRowIDPresentInList = selectedIDs.Contains(rowOrgID);
        // add to list
        if (emailCheckBox.Checked && !isRowIDPresentInList)
        {
            selectedIDs.Add(rowOrgID);
        }
        //remove from list
        if (!emailCheckBox.Checked && isRowIDPresentInList)
        {
            selectedIDs.Remove(rowOrgID);
        }
    }
    OriginalTable.PageIndex = e.NewPageIndex;
    BindTable();
    //we are now at the new page after paging
    //get the select ids and make the gridview checkbox checked accordingly
    foreach (GridViewRow row in OriginalTable.Rows)
    {
        var emailCheckBox = row.FindControl("HasEmail") as CheckBox;
        var rowOrgID = Convert.ToInt32(OriginalTable.DataKeys[row.RowIndex].Value);
        if (selectedIDs.Contains(rowOrgID))
        {
            emailCheckBox.Checked = true;
        }
    }
    Session["CheckedIDs"] = (selectedIDs.Count > 0) ? selectedIDs : null;
}

我们在这里使用Session来维护页面中的值。作为一个额外的优势,您将通过访问会话变量获取任何其他事件中的选中值。

<小时/> 的更新
如果您已经预先填充了HasEmail字段,请执行此操作以在初始化

时设置值
private void BindTable()
{
    DataTable table = GetTableFromDatabase();

    var selectedIDs = table.AsEnumerable()
        .Where(r => r.Field<bool>("HasEmail"))
        .Select(r => r.Field<int>("ORG_ID"))
        .ToList();
    if (selectedIDs != null && selectedIDs.Count > 0)
        Session["CheckedIDs"] = selectedIDs;

    OriginalTable.DataSource = table;
    OriginalTable.DataBind();
}