linq学习——分页

本文介绍了如何在ASP.NET中使用LINQ进行分页操作。通过定义一个名为`BindBoundControl`的方法来绑定数据源并实现分页,同时提供了方法的重载。示例中展示了如何调用这个方法来绑定员工数据,并展示在GridView控件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分页方法:

public void BindBoundControl<TSource>(IEnumerable<TSource> DataSource, GridView BoundControl, int PageSize,int PageIndex)
        {
            //获取总记录数(这里可以使用参数传入总页数 就不必每次都执行下面方法)
            int totalRecordCount = DataSource.Count();
            //计算总页数
            int totalPageCount = 0;
            if (PageSize == 0)
            {
                PageSize = totalRecordCount;
            }
            if (totalRecordCount % PageSize == 0)
            {
                totalPageCount = totalRecordCount / PageSize;
            }
            else
            {
                totalPageCount = totalRecordCount / PageSize + 1;
            }
            //从参数中获取当前页码
            int CurrentPageIndex = PageIndex;
            //如果从网址参数中获取页码不正确 设置页码为第一页
            //if (!int.TryParse(HttpContext.Current.Request.QueryString["Page"], out CurrentPageIndex) || CurrentPageIndex <= 0 || CurrentPageIndex > totalPageCount)
            //{
            //    CurrentPageIndex = 1;
            //}
            if (CurrentPageIndex <= 0 || CurrentPageIndex > totalPageCount)
            {
                CurrentPageIndex = 1;
            }
            //绑定数据源
            BoundControl.DataSource = DataSource.Skip((CurrentPageIndex - 1) * PageSize).Take(PageSize);
            BoundControl.DataBind();
        }

重载:

 public void BindBoundControl<TSource>(IEnumerable<TSource> DataSource, TSource type, GridView BoundControl, int PageSize, int PageIndex)
        {
            this.BindBoundControl(DataSource, BoundControl, PageSize,PageIndex);  
        }

调用:

 private void BindEmployees(int index)
        {
            Table<Employees> localDataTable;
            localDataTable = objCategories.selectEmployees();
            var list = (from em in localDataTable
                        orderby em.EmployeeID descending
                        select new
                        {
                            EmployeeID = em.EmployeeID,
                            LastName = em.LastName,
                            FirstName = em.FirstName,
                            Title = em.Title,
                            TitleOfCourtesy = em.TitleOfCourtesy
                        });
            BindBoundControl(list, this.GridView1, 5, index);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值