Sort template field in gridView

If you add a template field to your gridview, you will find that the default sort function do not work to sort your gridview based on the template field. It is actually rather easier to implement by adding and event, writing some code and adding a little bit of markup. Here is how

1. First change the markup of your template field.

Inside your template field, add this markup. You can do that in Code Edit or Design Mode.

<HeaderTemplate>
<asp:LinkButton ID=”LinkButton2″ runat=”server”  CommandName=”Sort” CommandArgument=”myDBfield” >Image</asp:LinkButton>
</HeaderTemplate>

2. Add RowCommand event to the gridview

Select GridView, click properties (F4) and go to events tab and click on RowCommand event. This will add yourgridviewName_RowCommand event.

3. Put this code in the event handler.

protected void gvCustomerFind_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals(“Sort”))
{
if (ViewState[“SortExpression”] != null)
{
if (this.ViewState[“SortExpression”].ToString() == e.CommandArgument.ToString())
{
if (ViewState[“SortOrder”].ToString() == “ASC”)
ViewState[“SortOrder”] = “DESC”;
else
ViewState[“SortOrder”] = “ASC”;
}
else
{
ViewState[“SortOrder”] = “ASC”;
ViewState[“SortExpression”] = e.CommandArgument.ToString();
}
}
else
{
ViewState[“SortExpression”] = e.CommandArgument.ToString();
ViewState[“SortOrder”] = “ASC”;
}
}
gvCustomerFind.DataBind(); // Bind your gridview *important*
}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s