ASP.Net - VB - GridView Paging Example

The following code snippet demonstrates how to apply paging to a GridViewcontrol using the PageIndexChanging event.
  1. // Default.aspx
  2.  
  3. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
  4.  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6.  
  7. <html xmlns="http://www.w3.org/1999/xhtml">
  8. <head runat="server">
  9.     <title>GridView Paging Example</title>
  10. </head>
  11. <body>
  12.     <form id="form1" runat="server">
  13.     <div>
  14.         <asp:GridView ID="Contacts" runat="server" AllowPaging="true" OnPageIndexChanging="PageIndexChanging" />
  15.     </div>
  16.     </form>
  17. </body>
  18. </html>
  19.  
  20. // Default.aspx.vb
  21.  
  22. Imports System.Data
  23. Imports System.Data.SqlClient
  24.  
  25. Partial Class _Default
  26.     Inherits System.Web.UI.Page
  27.  
  28.     Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
  29.         Me.BindGridView()
  30.     End Sub
  31.  
  32.     Private Sub BindGridView()
  33.         Dim provider As String = "Data Source=;Initial Catalog=AdventureWorks;Integrated Security=True"
  34.         Dim con As New SqlConnection(provider)
  35.  
  36.         Try
  37.             con.Open()
  38.             Dim cmd As New SqlCommand("SELECT FirstName, MiddleName, LastName, EmailAddress FROM Person.Contact", con)
  39.             Dim table As New DataTable()
  40.             Dim adapter As New SqlDataAdapter(cmd)
  41.             adapter.Fill(table)
  42.  
  43.             Contacts.DataSource = table
  44.             Contacts.DataBind()
  45.         Catch ex As Exception
  46.             Response.Write(ex.Message)
  47.         End Try
  48.     End Sub
  49.  
  50.     Protected Sub PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
  51.         Contacts.PageIndex = e.NewPageIndex
  52.         Contacts.DataBind()
  53.     End Sub
  54.  
  55. End Class

No comments:

Post a Comment