3

I have a gridview which I want to sort when any of its column header is clicked. There is a DataTable that is built on runtime and assigned to the gridview to populate data. Here is the DataTable and Gridview:

DataTable dtMedication = new DataTable();
dtClientMedications.Columns.Add("Id");
dtClientMedications.Columns.Add("BrandName");
dtClientMedications.Columns.Add("GenericName");
dtClientMedications.Columns.Add("Dosage");
dtClientMedications.Columns.Add("Physician");
dtClientMedications.Columns.Add("DatePrescribed");
dtClientMedications.Columns.Add("Status");
dtClientMedications.Columns.Add("ClientMedicationDataId");

<asp:GridView ID="gdvMainList" runat="server" AutoGenerateColumns="False"
                            SkinID="PagedGridView" onrowcommand="gdvMainList_RowCommand" 
                            DataKeyNames="Id" onsorting="gdvMainList_Sorting">
                            <PagerStyle CssClass="gridpager" HorizontalAlign="Right" />
                            <Columns>
                                <ucc:CommandFieldControl HeaderText="Actions" ShowDeleteButton="true" ButtonType="Image"
                                    DeleteImageUrl="~/App_Themes/Default/images/delete.png" ShowEditButton="true"
                                    EditImageUrl="~/App_Themes/Default/images/edit.png" DeleteConfirmationText="Are you sure you want to delete?">
                                    <ItemStyle HorizontalAlign="Center" Width="60px" />
                                </ucc:CommandFieldControl>
                                <asp:BoundField DataField="BrandName" HeaderText="Brand Name" />
                                <asp:BoundField DataField="GenericName" HeaderText="Generic Name" />
                                <asp:BoundField DataField="Dosage" HeaderText="Dosage" />
                                <asp:BoundField DataField="Physician" HeaderText="Physician" />
                                <asp:BoundField DataField="DatePrescribed" HeaderText="Date Prescribed" />
                                <asp:BoundField DataField="Status" HeaderText="Status" />
                                <asp:TemplateField HeaderText="">
                                    <ItemStyle CssClass="HiddenCol" Width="0px" />
                                    <HeaderStyle CssClass="HiddenCol" />
                                    <ItemTemplate>
                                        <asp:HiddenField ID="hdfClientMedicationDataId" runat="server" Value='<%#Bind("ClientMedicationDataId") %>' />
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <EmptyDataTemplate>
                                <div class="divEmptyGrid">
                                    --- No Medication Exists ---
                                </div>
                            </EmptyDataTemplate>
                        </asp:GridView>

enter image description here

2
  • what seems to the problem in doing so? what do you have in gdvMainList_Sorting? Commented Sep 6, 2011 at 8:58
  • I haven't written anything in that event handler yet. Problem is I dnt know how to handle that event according to my grid and datatable Commented Sep 6, 2011 at 9:07

2 Answers 2

9

First step to set AllowSorting property of GridView to true then add SortExpression property for each column you would to use for sorting:

SortExpression property indicates the expression that should be used to sort the data when that field's sorting header link is clicked

Let's consider BoundField from your code above, I have added a SortExpression property with value set to BrandName which means that when the column header for BrandName will be clicked column 'BrandName' in your DataTable will be used to sort the data:

Now in gdvMainList_Sorting event you have to rebind the grid to sorted data:

protected void gdvMainList_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
{
    //Using DataView for sorting DataTable's data
    DataView view = dtMedication.DefaultView;
    view.Sort = String.Format("{0} {1}", e.SortExpression, GetSortingDirection());
    gdvMainList.DataSource = view;
    gdvMainList.DataBind();
}

If you have noticed I have used getSortingDirection(), which a method that returns either 'ASC' or 'DESC' for sorting data in either ascending or descending order, respectively.

protected string GetSortingDirection() 
{
    if(ViewState["SortDirection"] == null)
        ViewState["SortDirection"] = "ASC";
    else if(ViewState["SortDirection"] == "ASC")
        ViewState["SortDirection"] = "DESC";
    else
        ViewState["SortDirection"] = "ASC";

    return ViewState["SortDirection"];
}

Some useful links:

  1. GridView sorting using VB.net
  2. Sorting and Paging tutorial
Sign up to request clarification or add additional context in comments.

1 Comment

One snippit of code I added in the sorting event handler was if(viewState["SortColumn"] <> e.SortExpressions) ViewState["sortDirection"] = null; ViewState["SortColumn"] = e.SortExpression; This defaults back to ASC when you click on a different column
0

For sorting the rows of the grid view you should use the SortDescription class constructor and passing two arguments to this class namely, sortby value and also the direction of sorting. Refer to the Sort gridrows based on column click for more details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.