Featured Post

Step Wise Project Planning

Planning is the most difficult process in project management. The framework described is called the Stepwise method to help to distinguis...

  1. Home

Showing data in a DataGrid server control with paging enabled (VB only)

 Imports System.Data.SqlClient

Imports System.Data


Partial Class _Default

    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then

            BindData()

        End If

    End Sub


    Private Sub BindData()

        Dim connectionString As String = "Your_Connection_String_Here"

        Dim query As String = "SELECT * FROM YourTable"


        Using connection As New SqlConnection(connectionString)

            Using command As New SqlCommand(query, connection)

                Dim adapter As New SqlDataAdapter(command)

                Dim dataTable As New DataTable()

                adapter.Fill(dataTable)


                DataGrid1.DataSource = dataTable

                DataGrid1.DataBind()

            End Using

        End Using

    End Sub


    Protected Sub DataGrid1_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged

        DataGrid1.CurrentPageIndex = e.NewPageIndex

        BindData()

    End Sub

End Class

=========================================================================
In this example:
  1. The BindData method is called in the Page_Load event handler to populate the DataGrid with data when the page is first loaded.

  2. The BindData method establishes a connection to the database, executes the SQL query to fetch data, fills the retrieved data into a DataTable, sets the DataTable as the DataSource of the DataGrid, and finally binds the DataGrid to display the data.

  3. The DataGrid1_PageIndexChanged event handler is used to handle paging. It updates the CurrentPageIndex property of the DataGrid to the new page index selected by the user and then calls the BindData method to re-bind the DataGrid with data for the selected page.

Make sure to replace "Your_Connection_String_Here" with your actual database connection string, and "YourTable" with the name of your database table. Additionally, adjust the SQL query as needed to fetch the desired data from your database.

Previous
Next Post »