Library tutorials & articles

Web Forms DataGrid and DataSet Programming

Sorting a View

Sorting can be implemented in the ORDER BY clause of the SELECT statement or by manipulating a View. The DataGrid supports _dynamic_ sorting on column headings with the AllowSorting property and binding to a View. If the AllowSorting property is set to true, the DataGrid will generate a heading button on each data column. It is up to you to add the logic to implement the sorting behavior in the DataGrid1_Sort event handler. To implement sorting (and filtering) you bind the DataGrid to a View, not directly to a table in the DataSet. You can dynamically set the Sort property in the View and then refresh the DataGrid to reflect the new sort order by calling DataBind(). In this project, sorting can be "toggled" in ascending (ASC) and descending (DESC) order. Each time the user clicks on the same column heading, the sort order reverses. This feature is accomplished by storing the LastSortColumn and LastSortOrder in the ViewState.

Register the OnSortCommand Event Handlers

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

<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 Sort Button to the DataGrid

Using the Design view, you can add a "Sort" button to the DataGrid by setting the "AllowSorting" property to true. That's it!

Persist the Sort Order and Sort Column to the ViewState

In order to support toggling on the sort button, you must persist the state of the sorting algorithm to the ViewState. It is sufficient to persist the LastSortColumn and LastSortOrder to the ViewState in our sort event handler and refresh these values in our Page_Load function. Here is the Page_Load function:

private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    // This code execute every time
    sqlDataAdapter1.Fill(dataSet11);
    view = dataSet11.Tables[0].DefaultView;
    textBoxMessage.Text= "";
       
    // This code executes the first time only
    if (!IsPostBack)
    {                                
        ViewState["LastSortOrder"]="ASC";
        ViewState["LastSortColumn"]= "au_id";
        ViewState["LastFilter"]= "";
        view.Sort = "au_id"+ " ASC";
        DataGrid1.DataBind();
    }
    else
    // This code executes only on post back
    {
        string lastSortColumn= (string)ViewState["LastSortColumn"];
        string lastSortOrder= (string)ViewState["LastSortOrder"];
        string lastFilter= (string)ViewState["LastFilter"];
        view.Sort= lastSortColumn+ " "+ lastSortOrder;
        view.RowFilter= lastFilter;
    }
}

On the initial page load, you initialize the LastSortOrder and LastSortColumn to "ASC" and "au_id".

    // This code executes the first time only
    if (!IsPostBack)
    {                                
        ViewState["LastSortOrder"]="ASC";
        ViewState["LastSortColumn"]= "au_id";
        ViewState["LastFilter"]= "";
        view.Sort = "au_id"+ " ASC";
        DataGrid1.DataBind();
    }

On post back, you reload the latest sort values from the ViewState:

    else
    // This code executes only on post back
    {
        string lastSortColumn= (string)ViewState["LastSortColumn"];
        string lastSortOrder= (string)ViewState["LastSortOrder"];
        string lastFilter= (string)ViewState["LastFilter"];
        view.Sort= lastSortColumn+ " "+ lastSortOrder;
        view.RowFilter= lastFilter;
    }

Add the Event Handlers to WebForm1.aspx.cs

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

protected void DataGrid1_Sort(Object sender, DataGridSortCommandEventArgs e)
{
    string newSortColumn= e.SortExpression.ToString();
    string newSortOrder="ASC"; // default
    string lastSortColumn= (string)ViewState["LastSortColumn"];
    string lastSortOrder= (string)ViewState["LastSortOrder"];
    if (newSortColumn.Equals(lastSortColumn) && lastSortOrder.Equals("ASC"))
    {
        newSortOrder= "DESC";    
    } // else {newSortOrder="ASC";}
    ViewState["LastSortOrder"]= newSortOrder;
    ViewState["LastSortColumn"]= newSortColumn;
    view.Sort= newSortColumn+ " "+ newSortOrder;
    DataGrid1.EditItemIndex = -1;
    DataGrid1.CurrentPageIndex= 0; // goto first page
    DataGrid1.DataBind();
}

This algorithm will support toggling on the sort column. The new sort property is constructed and passed to the View:

view.Sort= newSortColumn+ " "+ newSortOrder;

Note the need to persist the "new" sort order and sort column to the ViewState:

ViewState["LastSortOrder"]= newSortOrder;
ViewState["LastSortColumn"]= newSortColumn;

Finally, you reset the page index to the first page and call DataBind() to refresh the DataGrid with the updated View:

DataGrid1.EditItemIndex = -1;
DataGrid1.CurrentPageIndex= 0; // goto first page
DataGrid1.DataBind();

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