C# DataGridView を使ってバインディングナビゲーターで簡単なページ機能を実装する
バインディングナビゲーターで簡単なページング機能を使用するには、次の手順に従います。
- フォームに、DataGridViewコントロールとBindingNavigatorコントロールを追加します。
- フォームの ロード イベントで、 データソースを使用して DataGridView コントロールにデータを設定し、 BindingNavigator コントロールの BindingSource プロパティを、 DataGridView コントロールのデータソースに設定します。
- AllowUserToAddRows、AllowUserToDeleteRows、SelectionModeなどのDataGridViewコントロールのプロパティを設定する。
- BindingNavigator コントロールの AddNewItem、DeleteItem、CountItem などのプロパティを設定する
- バインディングナビゲータコントロールのイベントで、前のページボタンと次のページボタンのクリックイベントハンドラを追加してください。
- イベントハンドラーで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 を使用し、1 ページに 10 件のレコードを表示しています。pageSize とデータソースは必要に応じて変更できます。