实现GridView翻页并且实现CheckBox选中功能的保持

在GridView与数据库进行绑定后,由得到的数据记录可能有许多条,以至一个页面无法容纳,这时需要进行多页显。

要实现分页显现,只要使用分页类 "PagedDataSource" 或者只对GridView的AllowPaging属性设为true。即可

一般情况下,如下代码可以实现分页显示。   //使第一种方法:PagedDataSource类加上Linq技术来实现           

 

 

    //页面代码:--------------------------------




 

<table cellpadding="0" cellspacing="0" class="style2" border="1" style="margin-left: 100px;">
        <tr class="style3" style="background-color: #659ACE">
            <td colspan="2">
                &gt;&gt;<span class="style4">创建地址本</span>
                <asp:Label ID="lblsuccedd" runat="server" Style="margin-left: 400px" ForeColor="Red"></asp:Label>
            </td>
        </tr>
        <tr class="style3">
            <td class="style9">
                &nbsp;&nbsp; 地址本名称:
            </td>
            <td class="style8">
                <asp:TextBox ID="txtBookName" runat="server" Width="211px"></asp:TextBox>
                <asp:Button ID="BtnCreateBook" runat="server" Text="创建" Width="49px" Style="margin-left: 40px;"
                    OnClick="BtnCreateBook_Click" />
                <asp:RequiredFieldValidator ID="RFValiTotxtBookName" runat="server" Display="Dynamic"
                    ControlToValidate="txtBookName" ErrorMessage="地址本名不能为空!" Style="margin-left: 100px"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr class="style3">
            <td class="style10">
                &nbsp;&nbsp; 备注:
            </td>
            <td class="style6">
                <asp:TextBox ID="txtRemark" runat="server" Height="82px" TextMode="MultiLine" Width="213px">这家伙什么也没有留下!</asp:TextBox>
            </td>
        </tr>
        <tr class="style3">
            <td class="style10">
                &nbsp;&nbsp; 选择联系人:
            </td>
            <td class="style5">
                <asp:GridView ID="GVShow" runat="server" AutoGenerateColumns="False" Width="100%"
                    BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3"
                    CellSpacing="1" GridLines="None" DataKeyNames="Userid" PageSize="5">
                    <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                    <Columns>
                        <asp:TemplateField ItemStyle-Width="50px" HeaderStyle-Width="50px">
                            <HeaderTemplate>
                                <input id="CheckAll" type="checkbox" onclick="CheckBoxAll();" />
                            </HeaderTemplate>
                            <ItemTemplate>
                                <center>
                                    <asp:CheckBox ID="userCheck" runat="server" onclick="ForCheckBox();" />
                                </center>
                            </ItemTemplate>
                            <HeaderStyle Width="50px"></HeaderStyle>
                            <ItemStyle Width="50px"></ItemStyle>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                登陆名
                            </HeaderTemplate>
                            <ItemTemplate>
                                <%# eval_r("LoginName") %>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                昵称
                            </HeaderTemplate>
                            <ItemTemplate>
                                <%# eval_r("UserName") %>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                性别
                            </HeaderTemplate>
                            <ItemTemplate>
                                <%# WebHelp.StrSex(eval_r("UserSex").ToString()) %>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <HeaderTemplate>
                                电话
                            </HeaderTemplate>
                            <ItemTemplate>
                                <%# eval_r("UserPhone") %>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                    <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                    <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                    <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                    <EmptyDataTemplate>
                        没有任何注册用户信息
                    </EmptyDataTemplate>
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <asp:Button ID="btnPageTop" runat="server" Text="上一页" OnClick="btnPageTop_Click"
                    CausesValidation="false" />
                <asp:Button ID="btnPageDec" runat="server" Text="下一页" OnClick="btnPageDec_Click"
                    CausesValidation="false" />
                <asp:DropDownList ID="drpList" runat="server">
                </asp:DropDownList>
                <asp:Button ID="btnPages" runat="server" Text="跳转" OnClick="btnPages_Click" CausesValidation="false" />
                &nbsp;&nbsp; 第<asp:Label ID="lblPageCurrent" runat="server" Text="1"></asp:Label>
                页 / 共<asp:Label ID="lblPageCount" runat="server" Text=""></asp:Label>
                页
            </td>
        </tr>
    </table>


 

//底层逻辑---------------------------     //使第一种方法:PagedDataSource类加上Linq技术来实现

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Common_CreateAddressBook : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
            // 注意一定要先  将Session["check"]转换成List<String> 类型
            Session["check"] = new List<String>();
        }
    }

    //绑定GridView
    private void BindGridView()
    {
        //Linq To Sql
        DataClassesDataContext dc = new DataClassesDataContext();
        var dome = from info in dc.Userinfo where info.Roleid == 0 select info;
        //分页类
        PagedDataSource pds = new PagedDataSource();
        //打开分页功能
        pds.AllowPaging = true;
        //数据源
        pds.DataSource = dome.ToList();
        //每页显示数据
        pds.PageSize = 5;
        //当前页
        pds.CurrentPageIndex = int.Parse(lblPageCurrent.Text) - 1;
        //显示总页数
        lblPageCount.Text = pds.PageCount.ToString();
        //在下拉列表中添加数据
        drpList.Items.Clear();
        for (int i = 1; i <= pds.PageCount; i++)
        {
            drpList.Items.Add(i.ToString());
        }
        //同步当前页
        drpList.SelectedIndex = int.Parse(lblPageCurrent.Text) - 1;
        //按钮问题
        btnPageTop.Enabled = true;
        btnPageDec.Enabled = true;
        if (lblPageCurrent.Text == "1")
        {
            btnPageTop.Enabled = false;
        }
        if (lblPageCurrent.Text == (pds.PageCount).ToString())
        {
            btnPageDec.Enabled = false;
        }
        GVShow.DataSource = pds;
        GVShow.DataBind();

        SelectCheckBoxKeep();

    }

    //上一页
    protected void btnPageTop_Click(object sender, EventArgs e)
    {
        PageKeepCheckBox();
        lblPageCurrent.Text = (int.Parse(lblPageCurrent.Text) - 1).ToString();
        BindGridView();
    }
    //下一页
    protected void btnPageDec_Click(object sender, EventArgs e)
    {
        PageKeepCheckBox();
        lblPageCurrent.Text = (int.Parse(lblPageCurrent.Text) + 1).ToString();
        BindGridView();
    }
    protected void btnPages_Click(object sender, EventArgs e)
    {
        PageKeepCheckBox();
        lblPageCurrent.Text = drpList.Text;
        BindGridView();
    }


    /// <summary>
    /// GridView翻页与checkbox保持功能的实现     当点击翻页时保存数据发生
    /// </summary>
    private void PageKeepCheckBox()
    {
        List<string> lis = new List<string>();
        lis = Session["check"] as List<String>;
        string str = "";
        //循环GridView中的每一行
        foreach (GridViewRow item in GVShow.Rows)
        {
            //取出DataKeyNames中绑定的数据    (DataKeys是取出DataKeyNames中的数据)
            str = (GVShow.DataKeys[item.RowIndex].Value).ToString();
            //查找每一行中的CheckBox按钮
            CheckBox Check = item.FindControl("userCheck") as CheckBox;

            //如果行中的CheckBox被选中,将选中的数据放到List中去
            if (Check.Checked)
            {
                //当List中不包含此数据
                if (!lis.Contains(str))
                {
                    lis.Add(str);
                }
            }
            //否则移除
            else
            {
                if (lis.Contains(str))
                {
                    lis.Remove(str);
                }
            }
        }

        if (lis != null || lis.Count > 0)
        {
            Session["check"] = lis;
        }
    }


    /// <summary>
    /// 将以前选中的所有项打上标记   在GridView显示之后发生
    /// </summary>
    private void SelectCheckBoxKeep()
    {
        int i = 0;
        //得到Session["check"]
        List<String> lis = Session["check"] as List<String>;
        //如果lis中有数据
        if (lis != null && lis.Count > 0)
        {
            foreach (GridViewRow item in GVShow.Rows)
            {
                i = Convert.ToInt32(GVShow.DataKeys[item.RowIndex].Value);
                //如果lis中包含此数据,就设置本行中的CheckBox控件为选中
                if (lis.Contains(i.ToString()))
                {
                    CheckBox check = item.FindControl("userCheck") as CheckBox;
                    check.Checked = true;
                }
            }
        }

    }
}



posted @ 2014-09-09 18:47  徐朗  阅读(430)  评论(0编辑  收藏  举报