Library tutorials & articles

Web Forms DataGrid and DataSet Programming

Default Paging

Default paging is easy to add using the DataGrid's built in support for paging. With default paging, all of the data is loaded into the DataSet, but only a page of data is displayed in the DataGrid.

A more efficient method is to use "custom paging". In a nutshell, custom paging is implemented using carefully constructed SQL Select statements with a sort index, a corresponding sort order and SQL7's TOP syntax. In custom paging, only a page of data is loaded into memory. The current page index must be manually persisted to the ViewState.

Register the Paging Event Handlers

If you look at the file WebForm1.aspx in the HTML view you will see where the OnPageIndexChanged property is set to the appropriate event handler. The DataGrid will use this property to register the button event handlers:

<asp:datagrid id=DataGrid1 style="Z-INDEX: 101; LEFT: 23px; POSITION: absolute; TOP: 221px" runat="server"
DataKeyField="au_id" DataSource="<%# view %>" Height="270px" Width="679px"
OnUpdateCommand="DataGrid1_Update" OnCancelCommand="DataGrid1_Cancel" OnEditCommand="DataGrid1_Edit"
OnDeleteCommand="DataGrid1_Delete" BorderColor="Blue" OnItemCommand="Item_Click" AllowSorting="True"
OnSortCommand="DataGrid1_Sort"
AllowPaging="True" OnPageIndexChanged="DataGrid1_Page" BackColor="#C0FFFF">

Add a Navigation Bar to the DataGrid

Using the Design view, you can add a navigation bar to the DataGrid by setting the DataGrid properties:

AllowCustomPaging --> False
AllowPaging --> True
PageSize --> 10

Add the Event Handler to WebForm1.aspx.cs

Finally, you need to add the paging event handler with the proper signature to the WebForm1.asp.cs file.

protected void DataGrid1_Page(Object sender, DataGridPageChangedEventArgs e)
{
    DataGrid1.CurrentPageIndex= e.NewPageIndex;
    DataGrid1.EditItemIndex = -1;
    ResetPageIndex(DataGrid1, view);
    DataGrid1.DataBind();
}

Note the call to disable editing by setting the EditItemIndex to -1. You should disable editing when the user pages to a different page or wrong "record" will be left in edit mode. Here again is the ResetPageIndex function. You should call this function on most any page that calls Fill and DataBind. In a multi use environment, you cannot rely on the DataGrid's persisted page index since the actual size of the DataSet may change on Fill(). ResetPageIndex checks for an invalid page index. If the page index is invalid, the function leaves the user on the last page.

// ResetPageIndex resets invalid page index to last page
// ASSERT grid and view NOT NULL
protected void ResetPageIndex(DataGrid grid, DataView view)
{
    // check for invalid page index
    if ((grid.CurrentPageIndex != 0) && (((grid.CurrentPageIndex)*grid.PageSize)>= view.Count))
    {
        // invalid so leave at last page
        if ((view.Count % grid.PageSize)== 0)
        { // ends on page border
            grid.CurrentPageIndex= (view.Count/grid.PageSize)-1;
        }
        else // partial page
        {
            grid.CurrentPageIndex= (view.Count/grid.PageSize);
        }
    }
}

Custom Paging

Default paging is fairly easy to implement! Custom paging is a bit more difficult. Here the SQL from another project that implements custom paging with a page size of one:

private void buttonFirst_Click(object sender, System.EventArgs e)
{
    string sqlCustomers= "Select TOP 1 CompanyName+' '+CustomerID AS sortKey,
CustomerID, CompanyName, City
From Customers WHERE (CompanyName LIKE @CompanyName+'%' OR CompanyName IS NULL)
AND (CustomerID LIKE @CustomerID+'%')
AND (City LIKE @City+'%' OR City IS NULL) ORDER BY sortKey ASC";
    string sqlOrders= "SELECT TOP 1 OrderID, CustomerID, OrderDate FROM Orders
WHERE (CustomerID = @CustomerID) ORDER BY OrderDate";
    NavigateCustomersTable(sqlCustomers,sqlOrders);        
}
private void buttonPrevious_Click(object sender, System.EventArgs e)
{
    string sqlCustomers= "Select TOP 1 CompanyName+' '+CustomerID AS sortKey,
CustomerID, CompanyName, City
From Customers WHERE (CompanyName+' '+CustomerID < @sortKey) AND (CompanyName
LIKE @CompanyName+'%' OR CompanyName IS NULL)
AND (CustomerID LIKE @CustomerID+'%') AND (City LIKE @City+'%' OR City IS NULL)
ORDER BY sortKey DESC";
    string sqlOrders= "SELECT TOP 1 OrderID, CustomerID, OrderDate FROM Orders
WHERE (CustomerID = @CustomerID) ORDER BY OrderDate";
    NavigateCustomersTable(sqlCustomers,sqlOrders);        
}
private void buttonNext_Click(object sender, System.EventArgs e)
{
    string sqlCustomers= "Select TOP 1 CompanyName+' '+CustomerID AS sortKey,
CustomerID, CompanyName, City
From Customers WHERE (CompanyName+' '+CustomerID > @sortKey) AND (CompanyName
LIKE @CompanyName+'%' OR CompanyName IS NULL)
AND (CustomerID LIKE @CustomerID+'%') AND (City LIKE @City+'%' OR City IS NULL)
ORDER BY sortKey ASC";            
    string sqlOrders= "SELECT TOP 1 OrderID, CustomerID, OrderDate FROM Orders
WHERE (CustomerID = @CustomerID) ORDER BY OrderDate";
    NavigateCustomersTable(sqlCustomers,sqlOrders);        
}
private void buttonLast_Click(object sender, System.EventArgs e)
{
    string sqlCustomers= "Select TOP 1 CompanyName+' '+CustomerID AS sortKey,
CustomerID, CompanyName, City
From Customers WHERE (CompanyName LIKE @CompanyName+'%' OR CompanyName IS NULL)
AND (CustomerID LIKE @CustomerID+'%')
AND (City LIKE @City+'%' OR City IS NULL) ORDER BY sortKey DESC";
    string sqlOrders= "SELECT TOP 1 OrderID, CustomerID, OrderDate FROM Orders
WHERE (CustomerID = @CustomerID)
ORDER BY OrderDate";
    NavigateCustomersTable(sqlCustomers,sqlOrders);        
}

Beware, the sort key cannot contain null able columns.

Comments

  1. 26 Jan 2006 at 14:50
    How could i do all this with untyped dataset from xml source? (no find methods etc..)
    Vjero
  2. 23 Nov 2005 at 14:26

    hi
    hey ppl i m   inserting some data manually in a dataview then i m sorting that dta via dataview.sort , sorting is taking place perfectly here but when i embed this data into a word document  then  i found that data is not  in sorted order as this supposed to be but it is in order in which it had typed...........so guys if u  have have any solution of this problem  then plz  mail me at aman_105@rediffmail.com

  3. 10 Nov 2005 at 09:33

    hello
     I am converting C#.net code into vb.net code .
     Sorting ASC or DESC  is not working .
     while degugging ,code work fine but i think some how dataset is not getting refreshed.
     I have commented these line  'view.RowFilter = lastFilter' .Is it require for sorting
     Execpt that everything is same
      please help me out .
                                                Thanks            
     

  4. 30 Jun 2005 at 02:13

    Hi.


    I dont know if this only a problem of mine, but when I hit a sort column the DataGridSortCommand happens twice.


    Should this happen? In my case it happens and so all the code in that event doesnt work properly...


    Could some help me out on this one?


    TIA,
    C.C.

  5. 10 Nov 2004 at 09:24
    How do I obtain ResetPageIndex? It is unknown to my installation of .NET or at least to the libraries I am using.
  6. 01 May 2004 at 12:13

    Jeff,


    Thanks a bunch!  I am new to ASP.NET programming and it was having a devil of a time getting my datagrid to sort -- your example provided the one missing link: the DataSource property should have been set to the view and not the dataset! Tanx again.


    --Babak

  7. 01 Jan 1999 at 00:00

    This thread is for discussions of Web Forms DataGrid and DataSet Programming.

Leave a comment

Sign in or Join us (it's free).

Jeff Louie

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

We'd love to hear what you think! Submit ideas or give us feedback