Click here to Skip to main content
13,090,930 members (47,875 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am trying to sort a column 'mem_id 'in already generated gridview. I dont get the result. Hereunder are my codes:

<asp:GridView ID="GridView2" runat="server"  HorizontalAlign="Center"  AutoGenerateColumns="False" allowpaging="True"  AllowSorting="True"
OnSorting="GridView2_Sorting" PageSize="12" onpageindexchanging="GridView2_PageIndexChanging" onselectedindexchanged="GridView2_SelectedIndexChanged"
  style="border-color: #808000; font-size:small; top: 176px; left: 27px; position: absolute; height: 75px; width:1350px" >

            <RowStyle HorizontalAlign="Center" />
            <Columns >
            <asp:BoundField DataField="mem_id" HeaderText="Mem_ID" sortexpression="Mem_id"/>
            <asp:BoundField DataField="mem_name" HeaderText="Mem Name"/>
            <asp:BoundField DataField="mobile" HeaderText="Cell No:"/>

code behind:

protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
GridView Gridview2 = (GridView)sender;
SqlDataSource ds = (SqlDataSource)Gridview2.DataSource;
ds.SelectCommand = ds.SelectCommand + " order by "
+ e.SortExpression;
Gridview2.DataSource = ds;

Can anyone guide me?
Posted 11-Jul-13 4:45am
Updated 11-Jul-13 4:51am
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Create a sort property for the Sorting type
public SortDirection sortProperty
            if (ViewState["SortingState"] == null)
                ViewState["SortingState"] = SortDirection.Ascending;
            return (SortDirection)ViewState["SortingState"];
            ViewState["SortingState"] = value;

and inside the Sorting method

dsProjects = projectDetails.GetProjectHistory(UserName);
       if (sortProperty == SortDirection.Ascending)
           sortProperty = SortDirection.Descending;
           sortingDirection = "Desc";
           sortProperty = SortDirection.Ascending;
           sortingDirection = "Asc";
       DataView sortedView = new DataView(dsProjects.Tables[0]);
       sortedView.Sort = e.SortExpression + " " + sortingDirection;
       gvProjectHistory.DataSource = sortedView;

also check this links, it may helps you[^][^]
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

this is very old method of viewstate i have new idea do this


when user click on row then get value of attribute that is lastsort and its value is asc

and when clicked change attribute style to
so second time you get desc and vice versa its working excellent for me.....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.170813.1 | Last Updated 11 Jul 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100