如何在启用了分页的gridview内维护控件的状态?

时间:2011-06-28 04:46:40

标签: c# asp.net state-management

我有一个包含4列的网格视图,包括一个列为Approve。批准具有一个复选框,该复选框将在绑定后重复数据集的所有行。我做了allowpaging = true& pageindexsize为10.现在,假设我选中第2行和第5行的复选框,然后转到第2页,然后返回第1页,我在第1页检查的复选框(第2行和第5行)将重置为未选中状态州。我知道原因,这是因为我们在onpageindexchanging事件上绑定了gridview。但即使我们从1页移动到另一页,有没有办法维持复选框的状态。

由于

4 个答案:

答案 0 :(得分:1)

您可以使用Session来维护这些值。需要向会话添加值并重新绑定复选框的单页索引更改事件。

以下是一些可以帮助您的链接

  1. http://forums.asp.net/p/1368550/2852029.aspx
  2. http://myaspsnippets.blogspot.com/2010/08/maintaining-state-of-checkboxes-while.html

答案 1 :(得分:0)

尝试,(您必须将两个事件Checkbox_Checked和Checkbox_PreRender设置为网格中的CheckBox控件。此外,必须在网格中设置DataKey,以便Checks数组中有一个索引。)

protected bool[] Checks
{
    get { return (bool[])(ViewState["Checks"] ?? new bool[totalLengthOfDataSource]); }
    set { ViewState["Checks"] = value; }
}

protected void Checkbox_Checked(object sender, EventArgs e)
{
    CheckBox cb = (CheckBox)sender;
    bool[] checks = Checks;
    checks[(int)GetRowDataKeyValue(sender)] = cb.Checked;
    Checks = checks;
}

protected void Checkbox_PreRender(object sender, EventArgs e)
{
    CheckBox cb = (CheckBox)sender;
    bool[] checks = Checks;
    cb.Checked = checks[(int)GetRowDataKeyValue(sender)];
}

这些在静态GridViewUtils类中效果最好。

public static GridViewRow GetRow(object sender)
{
    Control c = (Control)sender;
    while ((null != c) && !(c is GridViewRow))
        c = c.NamingContainer;
    return (GridViewRow)c;
}

/// <summary>
/// Get the Grid the row is in
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public static GridView GetGrid(this GridViewRow row)
{
    Control c = (Control)row;
    while ((null != c) && !(c is GridView))
        c = c.NamingContainer;
    return (GridView)c;
}

/// <summary>
/// Get the ID field value based on DataKey and row's index
/// </summary>
/// <param name="sender">Any web-control object in the grid view</param>
/// <returns></returns>
public static object GetRowDataKeyValue(object sender)
{
    try
    {
        GridViewRow row = GetRow(sender);
        GridView grid = row.GetGrid();
        return grid.DataKeys[row.RowIndex].Value;
    }
    catch
    {
        return null;
    }
}

答案 2 :(得分:0)

另一种方法:

  

在可绑定对象上创建名为“userSelected”(或类似)的bool属性   在可绑定列表对象上按对象ID创建索引器   在grid_RowDataBound上,将可绑定对象的ID作为属性添加到复选框   在grid_RowDataBound上还将复选框的checked属性设置为obj.userSelected   在chech_CheckChaged上使用索引器设置可绑定对象的userSelected属性

由于

答案 3 :(得分:0)

我尝试了来自@Chuck的PreRender技术,但它对我不起作用(VS2005,ASP.net2,SQLsrv2005)。也许技术太老了,但这就是客户所拥有的。

所以我尝试了简单的myaspsnippets技术,并进行了一些修改,它完美无缺!

我的网格视图

                <asp:GridView ID="gvFTUNSENT" runat="server" 
                    AutoGenerateColumns="False" CellPadding="4" ForeColor="Black" AllowSorting="False" CssClass="gvCSS" Width="100%"
                    DataKeyNames="StudentID,StudentUnitID" DataSourceID="sdsFTUNSENT" 
                    GridLines="None" AllowPaging="True" PageSize="10" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" 
                    OnPageIndexChanged="GridView_PageIndexChanged" 
                    OnPageIndexChanging="GridView_PageIndexChanging">
                    <RowStyle Wrap="True" Height="48px" />
                    <Columns>
...etc...
                    </Columns>
                    <FooterStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" Height="100%" />
                    <PagerStyle CssClass="cssPager" BackColor="#6B696B" ForeColor="White" HorizontalAlign="Left" Height="100%" />
                    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
                </asp:GridView>

我使用的Pageing方法是:

protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView gv = (GridView)sender;

    //saves a "copy" of the page before it's changed over to the next one
    SavePageState(gv);

    gv.PageIndex = e.NewPageIndex;
    gv.DataBind();
}

    protected void GridView_PageIndexChanged(object sender, EventArgs e)
    {
...your code to handle anything after the page has changed

                    gv.DataSource = dt;
                    gv.DataSourceID = null;
                    gv.DataBind();

                    //reload any checkboxes that were session saved in the page
                    LoadPageState(gv);
                }
            }
        }
    }

所以SAVE和LOAD方法如下:

private void SavePageState(GridView gv)
{
    ArrayList categoryIDList = new ArrayList();
    Int32 index = -1;
    foreach (GridViewRow row in gv.Rows)
    {
        HiddenField hfStudentUnitID = (HiddenField)row.FindControl("hfStudentUnitID");
        if (hfStudentUnitID != null)
        {
            if (hfStudentUnitID.Value.Length > 0)
            {
                index = Convert.ToInt32(hfStudentUnitID.Value.ToString()); //gv.DataKeys[row.RowIndex]["StudentUnitID"];
                bool result = ((CheckBox)row.FindControl("cbSEND")).Checked;

                // Check in the Session
                if (Session["CHECKED_ITEMS"] != null)
                    categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
                if (result)
                {
                    if (!categoryIDList.Contains(index))
                        categoryIDList.Add(index);
                }
                else
                    categoryIDList.Remove(index);
            }
        }
    }
    if (categoryIDList != null && categoryIDList.Count > 0)
        Session["CHECKED_ITEMS"] = categoryIDList;
}

private void LoadPageState(GridView gv)
{
    ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
    if (categoryIDList != null && categoryIDList.Count > 0)
    {
        foreach (GridViewRow row in gv.Rows)
        {
            HiddenField hfStudentUnitID = (HiddenField)row.FindControl("hfStudentUnitID");
            if (hfStudentUnitID != null)
            {
                if (hfStudentUnitID.Value.Length > 0)
                {
                    Int32 index = Convert.ToInt32(hfStudentUnitID.Value.ToString()); //gv.DataKeys[row.RowIndex]["StudentUnitID"];
                    if (categoryIDList.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)row.FindControl("cbSEND");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }
    }
}

要使这项功能正常工作,您需要将Paging方法调用放入GridView,将CheckBox ID从cbSEND更改为您正在使用的内容,并将HiddenField指向其他控件或值行的唯一标识符。 不要使用RowIndex,因为这在GridView的整个数据长度中并不是唯一的。

像魅力一样!