GridView高效分页和搜索功能的实现代码(3)


/// <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></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:页面加载函数,主要是在首次进入页面时,进行初始化,默认的获取所有的信息

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjdyfj.html