简体   繁体   English

在分页asp.net/c#上Gridview中复选框值的持久性

[英]persistence of checkbox values in Gridview on paging asp.net/c#

I want to persist the check box values on selection of items displayed in grid view. 我想在选择网格视图中显示的项目时保留复选框值。

This is the code in gridviewpage.aspx which creates the gridview: 这是gridviewpage.aspx中创建gridview的代码:

 <form id="form1" runat="server">
    <div>
       <asp:GridView ID="GridView1" runat="server" 
        AutoGenerateColumns = "False" Font-Names = "Arial" 
        Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"  
        HeaderStyle-BackColor = "green" AllowPaging ="True"   
        OnPageIndexChanging = "OnPaging1xxx" OnRowDataBound = "RowDataBound" 
            AllowSorting="True" DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" >
       <Columns>
        <asp:BoundField ItemStyle-Width = "150px" DataField = "CustomerID" 
               HeaderText = "CustomerID" ReadOnly="True" SortExpression="CustomerID" />
        <asp:BoundField ItemStyle-Width = "150px" DataField = "City" HeaderText = "City" 
               SortExpression="City"/>
        <asp:BoundField ItemStyle-Width = "150px" DataField = "Country" 
               HeaderText = "Country" SortExpression="Country"/>
        <asp:BoundField ItemStyle-Width = "150px" DataField = "PostalCode" 
               HeaderText = "PostalCode" SortExpression="PostalCode"/>
               <asp:TemplateField>
                <ItemTemplate>
                <asp:CheckBox id="CheckBox1" runat="server" onclick="Check_Click(this)"/>
                </ItemTemplate>
                <HeaderTemplate>
                <asp:CheckBox id="chkAll" runat="server" Text="Select All" onclick="checkAll(this)"/>
                </HeaderTemplate>
               </asp:TemplateField>
       </Columns> 
       <AlternatingRowStyle BackColor="#C2D69B"  />

<HeaderStyle BackColor="Green"></HeaderStyle>
    </asp:GridView> 
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="Data Source=SDANTURTHI-PC;Initial Catalog=ArticleDB;Integrated Security=True" 
            ProviderName="System.Data.SqlClient" 
            SelectCommand="SELECT [CustomerID], [City], [Country], [PostalCode] FROM [Customers]">
        </asp:SqlDataSource>
    </div>

This is the code in gridviewpage.aspx.cs 这是gridviewpage.aspx.cs中的代码

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Collections;
using System.IO.Compression;  

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {        
        ArrayList CheckBoxArray;
        if (ViewState["CheckBoxArray"] != null)
        {
            CheckBoxArray = (ArrayList)ViewState["CheckBoxArray"];
        }
        else
        {
            CheckBoxArray = new ArrayList();
        }

        if (IsPostBack)
        {
            int CheckBoxIndex;
            bool CheckAllWasChecked=false;
            CheckBox chkAll = (CheckBox)GridView1.HeaderRow.Cells[4].FindControl("chkAll");
            string checkAllIndex = "chkAll-" + GridView1.PageIndex;
            if (chkAll.Checked)
            {                
                if (CheckBoxArray.IndexOf(checkAllIndex) == -1)
                {
                    CheckBoxArray.Add(checkAllIndex);
                }
            }
            else 
            {
                if (CheckBoxArray.IndexOf(checkAllIndex) != -1)
                {
                    CheckBoxArray.Remove(checkAllIndex);
                    CheckAllWasChecked = true;
                }
            }
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    CheckBox chk = (CheckBox)GridView1.Rows[i].Cells[4].FindControl("CheckBox1");
                    CheckBoxIndex = GridView1.PageSize * GridView1.PageIndex + (i + 1);
                    if (chk.Checked)
                    {
                        if (CheckBoxArray.IndexOf(CheckBoxIndex) == -1 && !CheckAllWasChecked)
                        {
                            CheckBoxArray.Add(CheckBoxIndex);
                        }
                    }
                    else 
                    {
                        if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1 || CheckAllWasChecked)
                        {
                            CheckBoxArray.Remove(CheckBoxIndex);
                        }
                    }
                }
            }
        }
       ViewState["CheckBoxArray"] = CheckBoxArray;

       GridView1.DataBind();
    }  

    protected void OnPaging1xxx(object sender, GridViewPageEventArgs e)
    {

        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
        if (ViewState["CheckBoxArray"] != null)
        {
            ArrayList CheckBoxArray = (ArrayList)ViewState["CheckBoxArray"];
            string checkAllIndex = "chkAll-" + GridView1.PageIndex;

            if (CheckBoxArray.IndexOf(checkAllIndex) != -1)
            {
                CheckBox chkAll = (CheckBox)GridView1.HeaderRow.Cells[4].FindControl("chkAll");
                chkAll.Checked = true;
            }
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {

                if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    if (CheckBoxArray.IndexOf(checkAllIndex) != -1)
                    {
                        CheckBox chk = (CheckBox)GridView1.Rows[i].Cells[4].FindControl("CheckBox1");
                        chk.Checked = true;
                        GridView1.Rows[i].Attributes.Add("style","background-color:aqua");      
                    }
                    else
                    {
                        int CheckBoxIndex = GridView1.PageSize * (GridView1.PageIndex) + (i + 1);
                        if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1)
                        {
                            CheckBox chk = (CheckBox)GridView1.Rows[i].Cells[4].FindControl("CheckBox1");
                            chk.Checked = true;
                            GridView1.Rows[i].Attributes.Add("style", "background-color:aqua");
                        }
                    }
                }
            }
        }
    }
    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
        }
    }
}

It is not able to persist the values, but when i debug the checkboxarray and viewstate["checkboxarray"] seem to possessing the right values. 它不能持久保存这些值,但是当我调试checkboxarray和viewstate["checkboxarray"]似乎拥有正确的值。 I don't understand why it is not working. 我不明白为什么它不起作用。 Please help me. 请帮我。 Thank you in anticipation 谢谢你的期待

Do note that ViewState only "works" on the trip from the server to the browser. 请注意,ViewState仅在从服务器到浏览器的行程中“起作用”。 You can't expect it to still be there on the post back. 您不能指望它仍会留在发回邮件中。

Persisting it would require using Session. 坚持下去将需要使用Session。

EDIT 编辑

Anything that you want to get back to the server you need to either put it in a form 您想返回服务器的任何内容都需要以表格形式放置
-> It'll be in Request.Form["blabla"] ->它将在Request.Form [“ blabla”]中
or in the querystring (mypage.aspx?blabla=somevalue) 或在查询字符串中(mypage.aspx?blabla = somevalue)
-> It'll be in Request.QueryString["blabla"] ->将在Request.QueryString [“ blabla”]中

Those are the only two ways to get data from the server to your page. 这是将数据从服务器获取到页面的仅有的两种方法。

(Addendum: (附录:

This is slightly hidden from you when your controls trigger events that you handle in your code-behind cs file. 当控件触发您在代码隐藏的cs文件中处理的事件时,对您而言这是微不足道的。 ASP.NET wraps the controls in a form and does a post back -> you run your code -> an updated page is sent back) ASP.NET将控件包装在表单中,然后回发->您运行代码->发送回更新的页面)

EDIT 编辑

Your checkboxes are in Request.Form[..] as "CheckBox1xxx" with xxx being a row number. 您的复选框在Request.Form [..]中为“ CheckBox1xxx”,其中xxx为行号。 This row number will be relatively meaningless to you. 该行号对您而言将毫无意义。

My recommendation is to loop through the values in Request.Form and see which ones start with "CheckBox1" (like here ), extract the row number, get the value for "CustomerIDxxx" and use that to match with the correct Record. 我的建议是遍历Request.Form中的值,看看哪些以“ CheckBox1”开头(如此 ),提取行号,获取“ CustomerIDxxx”的值,并使用该值与正确的Record匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM