Click here to Skip to main content
15,904,877 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
c# code for sorting data in gridview on page load without clicking any button .data is filled from sql server 2005 database
Posted

As data is filled from database, you should use 'order by' clause in your query for getting sorted data and call that method(containing the query) in page load.
 
Share this answer
 
Source:
ASP
<asp:GridView ID="gridUserMaster" runat="server" AllowSorting="True" OnSorting="CustomersGridView_Sorting" 

CS:
C#
protected void CustomersGridView_Sorting(Object sender, GridViewSortEventArgs e)
    {
        try
        {
            DataTable datatable = (DataTable)ViewState["gridview_datasource"];
            if (datatable != null)
            {
                DataView dataview = new DataView(datatable);
                if ((ViewState["sortdirection"] == null || (SortDirection)ViewState["sortdirection"] == SortDirection.Descending))
                    ViewState["sortdirection"] = SortDirection.Ascending;
                else
                    ViewState["sortdirection"] = SortDirection.Descending;
                dataview.Sort = e.SortExpression + " " + convertsortdirection((SortDirection)ViewState["sortdirection"]);
                gridUserMaster.DataSource = dataview;
                gridUserMaster.DataBind();
            }
        }
        catch (Exception ex)
        {
            Err.ErrorLog(Server.MapPath("Logs/ErrorLog"), ex.Message);
            ClientScript.RegisterStartupScript(this.GetType(), "msg", "alert('" + ex.Message.ToString() + "');", true);
        }
    }


Get more detailed description on MSDN:
GridView Examples for ASP.NET 2.0: Paging and Sorting the GridView's Data[^]
Sorting Data in a GridView Web Server Control[^]

Similar thread:
How to sort data in GridView in asp.net[^]
How to sort data into GridView[^]
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900