首页主机资讯C#DataGridView使用BindingNavigator实现简单分页功能

C#DataGridView使用BindingNavigator实现简单分页功能

时间2023-11-16 08:06:02发布访客分类主机资讯浏览420
导读:要使用BindingNavigator实现简单的分页功能,可以按照以下步骤进行操作:1. 在窗体上添加一个DataGridView控件和一个BindingNavigator控件。2. 在窗体的Load事件中,使用数据源填充DataGridV...

要使用BindingNavigator实现简单的分页功能,可以按照以下步骤进行操作:
1. 在窗体上添加一个DataGridView控件和一个BindingNavigator控件。
2. 在窗体的Load事件中,使用数据源填充DataGridView控件,并将BindingNavigator控件的BindingSource属性设置为DataGridView控件的数据源。
3. 设置DataGridView控件的属性,包括AllowUserToAddRows、AllowUserToDeleteRows和SelectionMode等。
4. 设置BindingNavigator控件的属性,包括AddNewItem、DeleteItem和CountItem等。
5. 在BindingNavigator控件的Events中,添加点击“上一页”和“下一页”按钮的事件处理程序。
6. 在事件处理程序中,修改BindingSource控件的Position属性,实现数据的翻页。
以下是一个简单的示例代码:
```csharp
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 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 {
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 GetPersons()
{
// 示例数据
List persons = new List();
for (int i = 1; i

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

c#

若转载请注明出处: C#DataGridView使用BindingNavigator实现简单分页功能
本文地址: https://pptw.com/jishu/541453.html
常见字符串截取方式 什么是控制台应用程序(ConsoleApplication)

游客 回复需填写必要信息