要使用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和數據源。