C# DataTable 分页实现

public DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize, ref int a, ref int b, ref int c)//PageIndex表示第几页,PageSize表示每页的记录数
        {
            if (PageIndex == 0)
                return dt;//0页代表每页数据,直接返回

            DataTable newdt = dt.Copy();
            newdt.Clear();//copy dt的框架

            int rowbegin = (PageIndex - 1) * PageSize;
            int rowend = PageIndex * PageSize;

            if (rowbegin >= dt.Rows.Count)
                return newdt;//源数据记录数小于等于要显示的记录,直接返回dt

            if (rowend > dt.Rows.Count)
                rowend = dt.Rows.Count;
            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }
            var totalCount = dt.Rows.Count;
            a = dt.Rows.Count;
            b = PageIndex;
            c = (totalCount / PageSize) + (totalCount % PageSize > 0 ? 1 : 0);
            return newdt;
        }

 

        //跳转
        private void btn_Go_Click(object sender, EventArgs e)
        {
            try
            {
                int i = Convert.ToInt32(this.txt_Go.Text);
            }
            catch (Exception)
            {
                this.txt_Go.Text = string.Empty;
                MessageBox.Show(this, "页码输入有误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (this.txt_Go.Text.Equals(string.Empty) || Convert.ToInt32(this.txt_Go.Text) < 1 || Convert.ToInt32(this.txt_Go.Text) > sum)
            {
                this.txt_Go.Text = string.Empty;
                MessageBox.Show(this, "页码输入有误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            LoadData(Convert.ToInt32(this.txt_Go.Text));
            this.txt_Go.Text = string.Empty;
        }

        //跳转页面时,页数编辑框禁止输入非法数字
        private void txt_Go_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\b')//这是允许输入退格键? 
            {
                int len = txt_Go.Text.Length;
                if (len < 1 && e.KeyChar == '0')
                {
                    e.Handled = true;
                }
                else if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字? 
                {
                    e.Handled = true;
                }

            }
        }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值