實現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" οnclick="CheckBoxAll();" />
                            </HeaderTemplate>
                            <ItemTemplate>
                                <center>
                                    <asp:CheckBox ID="userCheck" runat="server" οnclick="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;
                }
            }
        }

    }
}



發佈了25 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章