Pagination Implementation in Windows Forms DataGridView
In Windows Forms, there is a need to display large datasets efficiently while maintaining user-friendliness. Pagination allows users to navigate through data records by dividing them into smaller subsets displayed as pages. This article explores how to achieve pagination in a DataGridView control within a Windows form.
Custom Control vs. DataGridView Properties
The DataGridView component does not provide a built-in pagination feature. Therefore, creating a custom control is not necessary. Instead, we can utilize the BindingNavigator control in conjunction with a custom data source that supports page breaks.
Implementation:
The below code snippet outlines the implementation of pagination in DataGridView:
private const int totalRecords = 43; private const int pageSize = 10; public Form1() { dataGridView1.Columns.Add(new DataGridViewTextBoxColumn { DataPropertyName = "Index" }); bindingNavigator1.BindingSource = bindingSource1; bindingSource1.CurrentChanged += new System.EventHandler(bindingSource1_CurrentChanged); bindingSource1.DataSource = new PageOffsetList(); }
The PageOffsetList class provides a custom IListSource which returns a list of page offsets based on the total number of records and the desired page size. When the user clicks on the "next page" button of the BindingNavigator, the bindingSource1_CurrentChanged event is triggered.
private void bindingSource1_CurrentChanged(object sender, EventArgs e) { int offset = (int)bindingSource1.Current; List<Record> records = new List<Record>(); for (int i = offset; i < offset + pageSize && i < totalRecords; i++) records.Add(new Record { Index = i }); dataGridView1.DataSource = records; }
Within the event handler, the current page offset is retrieved and used to fetch the desired page of records. The fetched records are then bound to the DataGridView control, effectively displaying the next page.
Conclusion:
By utilizing the BindingNavigator and a custom data source that supports pagination, we have implemented pagination functionality within a DataGridView control in a Windows form. This approach enables efficient navigation of large datasets, enhancing the user experience and making data manipulation more manageable.
The above is the detailed content of How to Implement Pagination in a Windows Forms DataGridView?. For more information, please follow other related articles on the PHP Chinese website!