How to Paging in DataGridView

The DataGridView class offers a wide range of properties that allow for customization of individual cells, rows, columns, and even borders. This level of customization empowers developers to tailor the appearance and behavior of the DataGridView to meet specific requirements.

In scenarios where a DataGridView contains a large number of rows, implementing paging functionalities can be beneficial. Paging allows for displaying a subset of the rows at a time, improving performance and user experience by avoiding the need to load and render all rows simultaneously.

Paging in a DataGridView

datagrid-paging

When implementing paging in a DataGridView, it's important to establish the boundaries or limits of each page, determining which rows should be displayed within the current page. By doing so, you can enable navigation through the pages and provide intuitive paging functionalities.

The following vb.net program showcases a method to programmatically implement paging in a Windows DataGridView control. In this example, the DataGridView is set to display a fixed number of five rows at a time. Two additional buttons are included to facilitate the navigation between pages, allowing users to browse through the available data.

Full Source VB.NET
Imports System.Data.SqlClient Public Class Form1 Dim pagingAdapter As SqlDataAdapter Dim pagingDS As DataSet Dim scrollVal As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True" Dim sql As String = "SELECT * FROM authors" Dim connection As New SqlConnection(connectionString) pagingAdapter = New SqlDataAdapter(sql, connection) pagingDS = New DataSet() connection.Open() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") connection.Close() DataGridView1.DataSource = pagingDS DataGridView1.DataMember = "authors_table" End Sub Private Sub button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button2.Click scrollVal = scrollVal - 5 If scrollVal <= 0 Then scrollVal = 0 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub Private Sub button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button3.Click scrollVal = scrollVal + 5 If scrollVal > 23 Then scrollVal = 18 End If pagingDS.Clear() pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table") End Sub End Class

Conclusion

By incorporating paging functionalities, you can enhance the performance, manageability, and user experience of the DataGridView control, particularly when dealing with large datasets.