发布时间:2025-12-11 01:11:35 浏览次数:1
要使用BindingNavigator实现简单的分页功能,可以按照以下步骤进行操作:
在窗体上添加一个DataGridView控件和一个BindingNavigator控件。
在窗体的Load事件中,使用数据源填充DataGridView控件,并将BindingNavigator控件的BindingSource属性设置为DataGridView控件的数据源。
设置DataGridView控件的属性,包括AllowUserToAddRows、AllowUserToDeleteRows和SelectionMode等。
设置BindingNavigator控件的属性,包括AddNewItem、DeleteItem和CountItem等。
在BindingNavigator控件的Events中,添加点击“上一页”和“下一页”按钮的事件处理程序。
在事件处理程序中,修改BindingSource控件的Position属性,实现数据的翻页。
以下是一个简单的示例代码:
public partial class Form1 : Form{private BindingSource bindingSource = new BindingSource();private int pageSize = 10; // 每页显示的记录数private int currentPage = 1; // 当前页码public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){// 使用数据源填充DataGridView控件// 可以使用自己的数据源替换下面的示例数据List<Person> persons = GetPersons();bindingSource.DataSource = persons;dataGridView1.DataSource = bindingSource;// 设置DataGridView控件的属性dataGridView1.AllowUserToAddRows = false;dataGridView1.AllowUserToDeleteRows = false;dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;// 设置BindingNavigator控件的属性bindingNavigator1.BindingSource = bindingSource;bindingNavigator1.AddNewItem.Enabled = false;bindingNavigator1.DeleteItem.Enabled = false;// 设置分页信息int pageCount = (int)Math.Ceiling(persons.Count / (double)pageSize);bindingNavigator1.CountItem.Text = "共 " + pageCount + " 页";bindingNavigator1.MoveFirstItem.Click += new EventHandler(MoveFirstItem_Click);bindingNavigator1.MovePreviousItem.Click += new EventHandler(MovePreviousItem_Click);bindingNavigator1.MoveNextItem.Click += new EventHandler(MoveNextItem_Click);bindingNavigator1.MoveLastItem.Click += new EventHandler(MoveLastItem_Click);}private void MoveFirstItem_Click(object sender, EventArgs e){currentPage = 1;bindingSource.Position = 0;}private void MovePreviousItem_Click(object sender, EventArgs e){if (currentPage > 1){currentPage--;bindingSource.Position -= pageSize;}}private void MoveNextItem_Click(object sender, EventArgs e){int pageCount = (int)Math.Ceiling(bindingSource.Count / (double)pageSize);if (currentPage < pageCount){currentPage++;bindingSource.Position += pageSize;}}private void MoveLastItem_Click(object sender, EventArgs e){int pageCount = (int)Math.Ceiling(bindingSource.Count / (double)pageSize);currentPage = pageCount;bindingSource.Position = (currentPage - 1) * pageSize;}private List<Person> GetPersons(){// 示例数据List<Person> persons = new List<Person>();for (int i = 1; i <= 100; i++){persons.Add(new Person { Id = i, Name = "Person " + i });}return persons;}}public class Person{public int Id { get; set; }public string Name { get; set; }}在这个示例中,我们使用一个包含100个Person对象的List作为数据源,每页显示10条记录。可以根据自己的需求修改pageSize和数据源。