Two way sorting of Web DataGrid


If we have a large amount of data in a datagrid, it will be useful for us if we having some kind of sorting mechanism in it so that we can look at whatever kind of record we want. We are going to implement the sorting procedure of a ASP.NET datagrid.

Let me take u step-by-step through the sorting process.

  1. First in the HTML declaration of the data grid, add the attribute called AllowSorting="True". Now you will get a hyperlink on all the column names.

  2. Go to the declaration of individual data bound columns and add the attribute called SortExpression and its value for the particular data field for that column. Now you will get a link for that particular column header.

  3. Now go to the events of the datagrid and create an event for the SortCommand.

  4. Go again to the datagrid declaration and add a attribute called OnSortCommand=true.

  5. Now in the code-behind, we write a code for the sort event in the datagrid.

    Public void DataGrid1_SortCommand (object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
    {
    //
    //
    }

  6. Now get the column name to be sorted using e.SortExpression.

  7. When you have the column name, you can sort the DataView using the column name. E.g

    When u get the dataset to be bounded to the datagrid. Create a DataView from it and use the Sort method of it.

    DataSet dsShippers;
    dsShippers=getNorthWindShippersData();
    DataView dvShippers=
    new DataView();
    dvShippers=dsShippers.Tables[0].DefaultView;
    if(SortWay%2==0)
         dvShippers.Sort=sortfield+" "+"ASC";
    else
         dvShippers.Sort=sortfield+" "+"DESC";
    SortWay++;
    dgShippers.DataSource=dvShippers;
    dgShippers.DataBind();

  8. Now go back to your HTML code, add an attribute for datagrid called onSortCommand and give the value of the function name of the sort command in the code behind.

    <DataGrid id="dgShippers" .. .. .. onSortCommand="DataGrid1_SortCommand" AllowSorting="true">

Now you have a two-way sorting datagrid. Hope this provides you with some knowledge about datagrid sorting. For the datagrid paging you can use the in built paging mechanism of the datagrid, which is quite satisfactory.


Similar Articles