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();

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Beware of bugs in the above code; I have only proved it correct, not tried it.” - Donald Knuth