温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

GridView中怎么实现高效分页和搜索功能

发布时间:2021-08-10 14:58:44 来源:亿速云 阅读:163 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关GridView中怎么实现高效分页和搜索功能,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

 一、前台布局


  <div>
    <div id="main">
    <div id="search">
       <table>
<tr>
<td>
    <asp:Label ID="lb" runat="server" Text="姓名"></asp:Label></td>
<td>
    <asp:TextBox ID="SearchName" runat="server"></asp:TextBox>
</td>
<td>
    <asp:Button ID="btnSearch" runat="server" Text="查询" onclick="PagerBtnCommand_OnClick" CommandName="search" />
</td>
<td>
    <asp:Button ID="btnReset" runat="server" Text="重置" onclick="btnReset_Click" />
</td>
</tr>
</table>
    </div>
    <div id="gridView">
     <asp:GridView ID="UserGridView" runat="server"  AutoGenerateColumns="false">
        <Columns>
        <asp:TemplateField HeaderText="用户名">
        <ItemTemplate>
            <asp:Label ID="UserName" runat="server" Text='<%#Eval("username") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="单位名称">
        <ItemTemplate>
            <asp:Label ID="DisplayName" runat="server" Text='<%#Eval("displayname") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="组织编码">
        <ItemTemplate>
            <asp:Label ID="OrgCode" runat="server" Text='<%#Eval("orgcode") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="组织名称">
        <ItemTemplate>
            <asp:Label ID="OrgName" runat="server" Text='<%#Eval("orgname") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
    </div>
    <div id="page">
    <table>
     <tr>
     <td>
      <asp:Label ID="lbcurrentpage1" runat="server" Text="当前页:"></asp:Label>
    <asp:Label ID="lbCurrentPage" runat="server" Text=""></asp:Label>
    <asp:Label ID="lbFenGe" runat="server" Text="/"></asp:Label>
    <asp:Label ID="lbPageCount" runat="server" Text=""></asp:Label>
    </td>
     <td>
     <asp:Label ID="recordscount" runat="server" Text="总条数:"></asp:Label>
      <asp:Label ID="lbRecordCount" runat="server" Text=""></asp:Label>
    </td>
    <td>
<asp:Button ID="Fistpage" runat="server" CommandName="" Text="首页" OnClick="PagerBtnCommand_OnClick" />
<asp:Button ID="Prevpage" runat="server" CommandName="prev" Text="上一页"
        OnClick="PagerBtnCommand_OnClick" />
<asp:Button ID="Nextpage" runat="server" CommandName="next" Text="下一页" OnClick="PagerBtnCommand_OnClick" />
<asp:Button ID="Lastpage" runat="server" CommandName="last" Text="尾页"
       key="last" OnClick="PagerBtnCommand_OnClick" />
</td>
    <td>
    <asp:Label ID="lbjumppage" runat="server" Text="跳转到第"></asp:Label>
    <asp:TextBox ID="GotoPage" runat="server" Width="25px"></asp:TextBox>
    <asp:Label ID="lbye" runat="server" Text="页"></asp:Label>
      <asp:Button ID="Jump" runat="server" Text="跳转" CommandName="jump" OnClick="PagerBtnCommand_OnClick" />
    </td>
</tr>
</table>
    </div>
    </div>
    </div>

布局的效果如下:

GridView中怎么实现高效分页和搜索功能

二、后台的代码实现

     我会一点一点向大家讲解清楚,这个分页的原理

     Members:这里主要定义几个全局的变量,主要用来记录信息的数量、页的数量和当前页

复制代码 代码如下:


#region Members
        const int PAGESIZE = 10;//每页显示信息数量
        int PagesCount, RecordsCount;//记录总页数和信息总条数
        int CurrentPage, Pages, JumpPage;//当前页,信息总页数(用来控制按钮失效),跳转页码
        const string COUNT_SQL = "select count(*)  from p_user";
        #endregion

Methods:  

1、GetRecordsCount:该方法主要用来获取当前信息的总数,有一个sqlSearch参数,默认的为default,即初始化页面时,查询所有信息的总条数,当用户输入要搜索的用户名进行检索时,获取符合用户检索条件的信息的总条数

复制代码 代码如下:


/// <summary>
       /// 获取信息总数
       /// </summary>
       /// <param name="sqlSearch"></param>
       /// <returns></returns>
       public static int GetRecordsCount(string sqlRecordsCount)
       {
           string sqlQuery;
           if (sqlRecordsCount == "default")
           {
               sqlQuery = COUNT_SQL;
           }
           else
           {
               sqlQuery = sqlRecordsCount;
           }
           int RecordCount = 0;
           SqlCommand cmd = new SqlCommand(sqlQuery, Conn());
           RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
           cmd.Connection.Close();
           return RecordCount;
       }

2、OverPage:该方法主要用来计算剩余页,当前设置的为每页显示10条数据,如何符合条件的数据有11条,则要显示2页

复制代码 代码如下:


/// <summary>
       /// 计算余页
       /// </summary>
       /// <returns></returns>
       public int OverPage()
       {
           int pages = 0;
           if (RecordsCount % PAGESIZE != 0)
               pages = 1;
           else
               pages = 0;
           return pages;
       }

3、ModPage:该方法也是用计算余页,主要用来防止SQL执行溢出

复制代码 代码如下:


/// <summary>
       /// 计算余页,防止SQL语句执行时溢出查询范围
       /// </summary>
       /// <returns></returns>
       public int ModPage()
       {
           int pages = 0;
           if (RecordsCount % PAGESIZE == 0 && RecordsCount != 0)
               pages = 1;
           else
               pages = 0;
           return pages;
       }

4、Conn:该方法用来创建数据连接对象,在使用的时候只需改成自己的数据库名即可 

复制代码 代码如下:


/// <summary>
        /// 数据连接对象
        /// </summary>
        /// <returns></returns>
        public static SqlConnection Conn()
        {
            SqlConnection conn = new SqlConnection("data source=.;initial catalog=DB_GSL_ZCW;Integrated Security=true");
            conn.Open();
            return conn;
        }

5、GridViewDataBind:该方法主要用来数据绑定,如果传入的参数为default则,默认的绑定所有的数据,否则,则绑定过滤过的数据

复制代码 代码如下:


/// <summary>
        /// GridView数据绑定,根据传入参数的不同,进行不同方式的查询,
        /// </summary>
        /// <param name="sqlSearch"></param>
        private void GridViewDataBind(string sqlSearch)
        {
            CurrentPage = (int)ViewState["PageIndex"];
            //从ViewState中读取页码值保存到CurrentPage变量中进行按钮失效运算
            Pages = (int)ViewState["PagesCount"];
            //从ViewState中读取总页参数进行按钮失效运算
            //判断四个按钮(首页、上一页、下一页、尾页)状态
            if (CurrentPage + 1 > 1)//当前页是否为首页
            {
                Fistpage.Enabled = true;
                Prevpage.Enabled = true;
            }
            else
            {
                Fistpage.Enabled = false;
                Prevpage.Enabled = false;
            }
            if (CurrentPage == Pages)//当前页是否为尾页
            {
                Nextpage.Enabled = false;
                Lastpage.Enabled = false;
            }
            else
            {
                Nextpage.Enabled = true;
                Lastpage.Enabled = true;
            }
            DataSet ds = new DataSet();
            string sqlResult;
            //根据传入参数sqlSearch进行判断,如果为default则为默认的分页查询,否则为添加了过滤条件的分页查询
            if (sqlSearch == "default")
            {
                sqlResult = "Select Top " + PAGESIZE + "user_serialid,username,displayname,orgcode,orgname from p_user where user_serialid not in(select top " + PAGESIZE * CurrentPage + " user_serialid from p_user order by user_serialid asc) order by user_serialid asc";
            }
            else
            {
                sqlResult = sqlSearch;
            }
            SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlResult, Conn());
            sqlAdapter.Fill(ds, "Result");
            UserGridView.DataSource = ds.Tables["Result"].DefaultView;
            UserGridView.DataBind();
            //显示Label控件lbCurrentPaget和文本框控件GotoPage状态
            lbCurrentPage.Text = (CurrentPage + 1).ToString();
            GotoPage.Text = (CurrentPage + 1).ToString();
            sqlAdapter.Dispose();
        }


6、Page_Load:页面加载函数,主要是在首次进入页面时,进行初始化,默认的获取所有的信息

复制代码 代码如下:


protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)//首次进行该页时,页面初始化
            {
                RecordsCount = GetRecordsCount("default");//默认信息总数
                PagesCount = RecordsCount / PAGESIZE + OverPage();//默认的页总数
                ViewState["PagesCount"] = RecordsCount / PAGESIZE - ModPage();//保存末页索引,比页总数小1
                ViewState["PageIndex"] = 0;//保存页面初始索引从0开始
                ViewState["JumpPages"] = PagesCount;
                //保存页总数,跳页时判断用户输入数是否超出页码范围
                //显示lbPageCount、lbRecordCount的状态
                lbPageCount.Text = PagesCount.ToString();
                lbRecordCount.Text = RecordsCount.ToString();
                //判断跳页文本框失效
                if (RecordsCount <= 10)
                {
                    GotoPage.Enabled = false;
                }
                    GridViewDataBind("default");//调用数据绑定函数TDataBind()进行数据绑定运算
            }
        }

7、PagerBtnCommand_OnClick:该方法主要用来处理设计视图页的“首页”、“下一页”,“上一页”,“尾页”,“查询”按钮的Click事件,主要通过不同按钮的CommandName属性来分别处理,需要在前台为每一个按钮相应的CommandName属性赋值,如果用户点击的是“查询”按钮,这个时候需要对查询的Sql语句进行重写,加入过滤条件,即用户输入的查询的条件

复制代码 代码如下:


/// <summary>
        /// 页面按钮Click处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PagerBtnCommand_OnClick(object sender, EventArgs e)
        {
            CurrentPage = (int)ViewState["PageIndex"];
            //从ViewState中读取页码值保存到CurrentPage变量中进行参数运算
            Pages = (int)ViewState["PagesCount"];//从ViewState中读取总页参数运算
            Button btn = sender as Button;
            string sqlResult="default";
            if (btn != null)
            {
                string cmd = btn.CommandName;
                switch (cmd)//根据不同的CommandName做出不同的处理
                {
                    case "next":
                        CurrentPage++;
                        break;
                    case "prev":
                        CurrentPage--;
                        break;
                    case "last":
                        CurrentPage = Pages;
                        break;
                    case "search":
                        if (!string.IsNullOrEmpty(SearchName.Text))
                        {
                            RecordsCount = GetRecordsCount("select count(*) from p_user where username like '" + SearchName.Text + "%'");//获取过滤后的总记录数
                            PagesCount = RecordsCount / PAGESIZE + OverPage();//该变量为页总数
                            ViewState["PagesCount"] = RecordsCount / PAGESIZE - ModPage();//该变量为末页索引,比页总数小1
                            ViewState["PageIndex"] = 0;//保存一个为0的页面索引值到ViewState,页面索引从0开始
                            ViewState["JumpPages"] = PagesCount;
                            //保存PageCount到ViewState,跳页时判断用户输入数是否超出页码范围
                            //显示lbPageCount、lbRecordCount的状态
                            lbPageCount.Text = PagesCount.ToString();
                            lbRecordCount.Text = RecordsCount.ToString();
                            //判断跳页文本框失效
                            if (RecordsCount <= 10)
                                GotoPage.Enabled = false;
                sqlResult = "Select Top " + PAGESIZE + "user_serialid,username,displayname,orgcode,orgname from p_user where user_serialid not in(select top " + PAGESIZE * CurrentPage + " user_serialid from p_user order by user_serialid asc) and username like '" + SearchName.Text + "%' order by user_serialid asc";
                        }
                        else
                        {
                            Response.Write("请输入您所要查找的用户姓名!");
                        }
                        break;
                    case "jump":
                       JumpPage = (int)ViewState["JumpPages"];
                      //从ViewState中读取可用页数值保存到JumpPage变量中
                      //判断用户输入值是否超过可用页数范围值
                      if(Int32.Parse(GotoPage.Text) > JumpPage ||      Int32.Parse(GotoPage.Text) <= 0)
Response.Write("<script>alert('页码范围越界!')</script>");
                      else
                      {
                          int InputPage = Int32.Parse(GotoPage.Text.ToString()) - 1;
                          //转换用户输入值保存在int型InputPage变量中
                          ViewState["PageIndex"] = InputPage;
                          CurrentPage = InputPage;
                         //写入InputPage值到ViewState["PageIndex"]中
                          sqlResult = "Select Top " + PAGESIZE + "user_serialid,username,displayname,orgcode,orgname from p_user where user_serialid not in(select top " + PAGESIZE * CurrentPage + " user_serialid from p_user order by user_serialid asc) and username like '" + SearchName.Text + "%' order by user_serialid asc";
                      }
                        break;
                    default:
                        CurrentPage = 0;
                        break;
                }
                ViewState["PageIndex"] = CurrentPage;
                //将运算后的CurrentPage变量再次保存至ViewState
                GridViewDataBind(sqlResult);//调用数据绑定函数TDataBind()
            }
        }

8、btn_Reset_Click:该方法主要用来进行重置,用户完成一次查询之后,需要重置,才能进行下一次的查询操作

复制代码 代码如下:


protected void btnReset_Click(object sender, EventArgs e)
     (
         RecordsCount = GetRecordsCount("default");//默认信息总数
         PagesCount = RecordsCount / PAGESIZE + OverPage();//默认的页总数
         ViewState["PagesCount"] = RecordsCount / PAGESIZE - ModPage();//保存末页索引,比页总数小1
         ViewState["PageIndex"] = 0;//保存页面初始索引从0开始
         ViewState["JumpPages"] = PagesCount;
         //保存页总数,跳页时判断用户输入数是否超出页码范围
         //显示lbPageCount、lbRecordCount的状态
         lbPageCount.Text = PagesCount.ToString();
         lbRecordCount.Text = RecordsCount.ToString();
         //判断跳页文本框失效
         if (RecordsCount <= 10)
         {
             GotoPage.Enabled = false;
         }
             GridViewDataBind("default");//调用数据绑定函数TDataBind()进行数据绑定运算
     }

关于GridView中怎么实现高效分页和搜索功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI