Gridview Sorting using attribute in C#

Hi All, many developers who try to sort a GridView generally use the ViewState for maintaining the last position of the GridView. Here, I’ll show you how to do the same thing without ViewState, using Attributes of Gridview.

<asp:GridView ID=”GridView1″
runat=”server” AllowSorting=”true”
AutoGenerateColumns=”False” onsorting=”GridView1_Sorting”
CurrentSortField=”employeeid” CurrentSortDirection=”ASC”
onrowcreated=”GridView1_RowCreated” AllowPaging=”true”
CaptionAlign=”Bottom” onpageindexchanging=”GridView1_PageIndexChanging”
<asp:BoundField DataField=”EmployeeId” HeaderText=”Last Name”
ItemStyle-Width=”15%” SortExpression=”EmployeeId” >

<ItemStyle Width=”15%”>
<asp:BoundField DataField=”Name”
HeaderText=”First Name” ItemStyle-Width=”15%”
SortExpression=”Name” >
<ItemStyle Width=”15%”>
<asp:BoundField DataField=”gender”
HeaderText=”Email” ItemStyle-Width=”15%” >
<ItemStyle Width=”15%”>
<asp:TemplateField HeaderText=”Change Password”


<asp:LinkButton ID=”imgbtn1″
runat=”server”>change password</asp:LinkButton>

<ItemStyle Width=”15%”></ItemStyle>
<asp:BoundField DataField=”city”
HeaderText=”Date created” ItemStyle-Width=”15%”>
<ItemStyle Width=”15%”></ItemStyle>
<PagerSettings Mode=”NextPreviousFirstLast” />

And I sort using the attribute property of the GridView.

See here, through attribute, I am maintaining last sorted record. Suppose last I sort asc then asc and if I last sorted desc then desc. This is how it works:

private void GridView1_Sorting (GridView gridview, GridViewSortEventArgs e,
out SortDirection sortDirection, out string sortField)
sortField = e.SortExpression;
sortDirection = e.SortDirection;
if (gridview.Attributes[“CurrentSortField”] != null &&
gridview.Attributes[“CurrentSortDirection”] != null)
if (sortField == gridview.Attributes[“CurrentSortField”])
if (gridview.Attributes[“CurrentSortDirection”] == “ASC”)
sortDirection = SortDirection.Descending;
sortDirection = SortDirection.Ascending;
gridview.Attributes[“CurrentSortField”] = sortField;
gridview.Attributes[“CurrentSortDirection”] =
(sortDirection == SortDirection.Ascending ? “ASC” : “DESC”);

In sorting, you have two options asc/desc. Now, if you are sorting by asc, then in gridview attribute add to CurrentSortDirection= asc. When user clicks for the second time, we get value from CurrentSortDirection asc so now do desc and add CurrentSortDirection = desc.

Now you will get the last sorted and filed easily and it generally shows that while developing, there is too much load on the page using the viewstate.


Leave a Reply

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

You are commenting using your 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