Example E2672
Visible to All Users

Grid View for ASP.NET Web Forms - How to bind the grid to an ObjectDataSource and enable server-side paging

The example demonstrates how to create ObjectDataSource with select parameters to allow ASPxGridView to perform paging and sorting using SQL queries to a database server.

Grid

The ObjectDataSource object supports SelectCountMethod and SelectMethod methods. Implement the methods to return the number of all records and records for the current page.

To enable server-side paging, set the DataSourceForceStandardPaging property to true.

Note that in this case, our advanced paging capabilities are turned off and the following grid features are not supported: summary calculation, data grouping, data filtering, unbound data (unbound columns), compound (complex) properties, endless paging mode, and conditional formatting.

Files to Review

Example Code

WebSite/App_Code/Products.cs(vb)
C#
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.ComponentModel; using System.Data.SqlClient; public class People { private static String _connectionString; private static Boolean _initialized; public static void Initialize() { // Initialize data source. Use "Northwind" connection string from configuration. if (ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"] == null || ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString.Trim() == "") { throw new Exception("A connection string named 'AdventureWorksConnectionString' with a valid connection string " + "must exist in the <connectionStrings> configuration section for the application."); } _connectionString = ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString; _initialized = true; } [DataObjectMethod(DataObjectMethodType.Select, true)] public static DataTable GetPeople(Int32 startRecord, Int32 maxRecords, String sortColumns) { VerifySortColumns(sortColumns); if (!_initialized) { Initialize(); } String sqlColumns = "[ContactID], [FirstName], [LastName], [EmailAddress], [Phone]"; String sqlTable = "[Person].[Contact]"; String sqlSortColumn = "[ContactID]"; if (!String.IsNullOrEmpty(sortColumns)) sqlSortColumn = sortColumns; String sqlCommand = String.Format( "SELECT * FROM (" + " SELECT ROW_NUMBER() OVER (ORDER BY {0}) AS rownumber," + " {1}" + " FROM {2}" + ") AS foo " + "WHERE rownumber >= {3} AND rownumber <= {4}", sqlSortColumn, sqlColumns, sqlTable, startRecord + 1, startRecord + maxRecords ); SqlConnection conn = new SqlConnection(_connectionString); SqlDataAdapter da = new SqlDataAdapter(sqlCommand, conn); DataSet ds = new DataSet(); try { conn.Open(); da.Fill(ds, "People"); } catch (SqlException e) { // Handle exception. } finally { conn.Close(); } if (ds.Tables["People"] != null) return ds.Tables["People"]; return null; } // columns are specified in the sort expression to avoid a SQL Injection attack. private static void VerifySortColumns(string sortColumns) { sortColumns = sortColumns.ToLowerInvariant().Replace(" asc", String.Empty).Replace(" desc", String.Empty); String[] columnNames = sortColumns.Split(','); foreach (String columnName in columnNames) { switch (columnName.Trim().ToLowerInvariant()) { case "contactid": case "firstname": case "lastname": case "emailaddress": case "phone": case "": break; default: throw new ArgumentException("SortColumns contains an invalid column name."); } } } public static Int32 GetPeopleCount() { if (!_initialized) { Initialize(); } string sqlCommand = "SELECT COUNT ([ContactID]) FROM [Person].[Contact]"; SqlConnection conn = new SqlConnection(_connectionString); SqlCommand command = new SqlCommand(sqlCommand, conn); SqlDataAdapter da = new SqlDataAdapter(sqlCommand, conn); Int32 result = 0; try { conn.Open(); result = (Int32)command.ExecuteScalar(); } catch (SqlException e) { // Handle exception. } finally { conn.Close(); } return result; } }
WebSite/Default.aspx
ASPx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Assembly="DevExpress.Web.v13.1, Version=13.1.14.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Namespace="DevExpress.Web" TagPrefix="dx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Bind a grid to a ObjectDataSource with EnablePaging</title> </head> <body> <form id="form1" runat="server"> <div> <dx:ASPxGridView ID="grid" runat="server" DataSourceForceStandardPaging="True" AutoGenerateColumns="False" DataSourceID="ods" KeyFieldName="ContactID"> <Columns> <dx:GridViewDataTextColumn FieldName="ContactID" VisibleIndex="0" ReadOnly="true"> <EditFormSettings Visible="False" /> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName="FirstName" VisibleIndex="1"> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName="LastName" VisibleIndex="2"> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName="EmailAddress" VisibleIndex="3"> </dx:GridViewDataTextColumn> <dx:GridViewDataTextColumn FieldName="Phone" VisibleIndex="4"> </dx:GridViewDataTextColumn> </Columns> </dx:ASPxGridView> <asp:ObjectDataSource ID="ods" runat="server" SortParameterName="sortColumns" EnablePaging="true" StartRowIndexParameterName="startRecord" MaximumRowsParameterName="maxRecords" SelectCountMethod="GetPeopleCount" SelectMethod="GetPeople" TypeName="People"></asp:ObjectDataSource> </div> </form> </body> </html>

Disclaimer: The information provided on DevExpress.com and affiliated web properties (including the DevExpress Support Center) is provided "as is" without warranty of any kind. Developer Express Inc disclaims all warranties, either express or implied, including the warranties of merchantability and fitness for a particular purpose. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.

Confidential Information: Developer Express Inc does not wish to receive, will not act to procure, nor will it solicit, confidential or proprietary materials and information from you through the DevExpress Support Center or its web properties. Any and all materials or information divulged during chats, email communications, online discussions, Support Center tickets, or made available to Developer Express Inc in any manner will be deemed NOT to be confidential by Developer Express Inc. Please refer to the DevExpress.com Website Terms of Use for more information in this regard.