本例在winform中封装了一个UserControl,主要使用了DataGridView,具备基本的分页跳转和显示功能:
新建一个UserControl,做下布局(本例取名:DataPager):
DataGridView用来显示数据,两个button用来上下翻页,两个lable分别显示数据总数、当前页码数
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Conf.UC
{
public partial class DataPager : UserControl
{
public DataPager()
{
InitializeComponent();
}
DataTable dataTable;
/// <summary>
/// 显示数据
/// </summary>
/// <param name="dt"></param>
public void ShowData(DataTable dt)
{
if (dt.Rows.Count > 0)
{
// 倒序
DataView dv = dt.DefaultView;
dv.Sort = "id desc";
DataTable dt2 = dv.ToTable();
this.dataTable = dt2;
this.page = 1;
}
}
/// <summary>
/// 总数
/// </summary>
int count
{
get
{
int value = dataTable.Rows.Count;
this.lb_count.Text = value.ToString();
return value;
}
}
/// <summary>
/// 总页数
/// </summary>
int total_page
{
get
{
return (int)Math.Ceiling((double)count / (double)limit);
}
}
int _page = 1;
/// <summary>
/// 当前页码
/// </summary>
int page
{
set
{
_page = value;
// 范围
if (_page < 1)
{
_page = 1;
}
if (_page > total_page)
{
_page = total_page;
}
// 显示数据
DataTable dt = new DataTable();
dt = dataTable.Clone();
int start = (_page - 1) * limit;
int end = start + limit;
end = end > count ? count : end;
for (int i = start; i < end; i++)
{
dt.Rows.Add(dataTable.Rows[i].ItemArray);
}
this.data.DataSource = dt;
// 显示页码
this.lb_page.Text = string.Format("{0}/{1}", _page, total_page);
this.btnPre.Enabled = (_page == 1) ? false : true;
this.btnNext.Enabled = (_page == total_page) ? false : true;
}
get { return _page; }
}
/// <summary>
/// 每页显示数
/// </summary>
int limit = 50;
// 上一页
private void btnPre_Click(object sender, EventArgs e)
{
page--;
}
// 下一页
private void btnNext_Click(object sender, EventArgs e)
{
page++;
}
}
}
若在vs工具箱列表中,没有出现刚刚自定义的UserControl,需要点击vs->项目->刷新项目工具箱项,即可刷新工具箱列表。