Gridview Sorting Using C#

Updated on 14 Sep 2012,
Published on 13 Mar 2008

ASP.Net 2.0 provides the sorting feature also in GridView Control. You can sort the records displayed using Gridview control in ascending or descending order retrieved from sql database. You can use C# code to bind the SQL data with GridView control and follow the following simple steps to make your ASP.Net GridView control with sorting enabled. 

GridView Examples:

You can see the live samples and examples of GridView from the following links:

First of all drag the GridView control from Data controls menu. It will add the GridView control HTML source code as given above. Now click on GridView control to load the control properties at right side panel.

<asp:GridView id="GridView1" runat="server"></asp:GridView>

To allow the sorting in GridView control select True from the dropdown list of AllowSorting property of Gridview as shown in above image.

This will add AllowSorting="True" in HTML source code of GridView Control.

Next step is to bind the Sorting event for GridView Control.

To bind the Sorting event of GridView control, double click on the Sorting event in the properties viewer of GridView. This will add the Sorting event in the HTML source code and C# code for Gridview.

HTML Source code for GridView Sorting

<asp:GridView ID="GridView1" 
              runat="server"
              CellPadding="2"
              AllowSorting="True" 
              OnSorting="GridView1_Sorting" 
              AutoGenerateColumns="False" 
              Width="500px">
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="ProductID" SortExpression="ProductName">
            <HeaderStyle HorizontalAlign="Left" />
        </asp:BoundField>

        <asp:BoundField DataField="ProductName" HeaderText="Product Name" SortExpression="ProductName">
            <HeaderStyle HorizontalAlign="Left" Width="200px" />
        </asp:BoundField>

        <asp:BoundField DataField="UnitsInStock" HeaderText="Units In Stock" SortExpression="UnitsInStock">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:BoundField>

        <asp:BoundField DataField="UnitPrice" HeaderText="Price Per Unit" SortExpression="UnitPrice">
            <HeaderStyle HorizontalAlign="Left" />
            <ItemStyle HorizontalAlign="Center" />
        </asp:BoundField>
    </Columns>
</asp:GridView>

C# Code for GridView Sorting

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["sortOrder"] = "";
            bindGridView("","");
        }
    }

    public void bindGridView(string sortExp,string sortDir)
    {
        // string variable to store the connection string
        // defined in ConnectionStrings section of web.config file.
        string connStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

        // object created for SqlConnection Class.
        SqlConnection mySQLconnection = new SqlConnection(connStr);

        // if condition that can be used to check the sql connection
        // whether it is already open or not.
        if (mySQLconnection.State == ConnectionState.Closed)
        {
            mySQLconnection.Open();
        }

        SqlCommand mySqlCommand = new SqlCommand("select top 10 ProductID, ProductName, UnitsInStock, UnitPrice from products", mySQLconnection);
        SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
        DataSet myDataSet = new DataSet();
        mySqlAdapter.Fill(myDataSet);

        DataView myDataView = new DataView();
        myDataView = myDataSet.Tables[0].DefaultView;

        if (sortExp!=string.Empty)
        {
            myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
        }

        GridView1.DataSource = myDataView;
        GridView1.DataBind();

        // if condition that can be used to check the sql connection
        // if it is open then close it.
        if (mySQLconnection.State == ConnectionState.Open)
        {
            mySQLconnection.Close();
        }

    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
      
        bindGridView(e.SortExpression, sortOrder);
        
    }

    public string sortOrder
    {
        get
        {
            if (ViewState["sortOrder"].ToString() == "desc")
            {
                ViewState["sortOrder"] = "asc";
            }
            else
            {
                ViewState["sortOrder"] = "desc";
            }

            return ViewState["sortOrder"].ToString();
        }
        set
        {
            ViewState["sortOrder"] = value;
        }
    }

Output:

Get the output for above discussed code from the following link:

ASP.Net GridView Sorting

Continue to next tutorial: ASP.Net Bind GridView to DataTable to learn how to bind the records stored in a datatable to gridview.

50 Responses to "Gridview Sorting Using C#"
harpreet
Helping Code....
Noora
Greate code, and easy to understand
but how can i add a sorting image to the header of the column, please help me
Doellinger
Great explanation. Usefull!!!
Asmat Khan
Very useful and easy to understand
I give you ALL STAR
Thanks
LSY
I'm having problem with the sorting ascending orerl
hi
simple and good..it works.easyly understandable and helpful
zameer
Very simple and very good...thanks for the info
Nilesh
Really Thanks
It's working helped me too much
Hussain chawalwala
Cool.........thanks mate....saved loads of time....
Very useful and easy to understand AND LEARN
I give you 5 STAR
Thanks
Elvin Asadov
thanks
Rakesh
I got the problem like "Object reference not set to an instance of an object" in if condition.

public string sortOrder
{
get
{
if (ViewState["sortOrder"].ToString() == "descending" )
{
MdKhan
Very Helpimg code. Thankx a lot
abc
good example and easy to understand
Raj
Thank you
KAGS
thanks a lot pal, this code helped well......
Aruna
This example brought me out of the hell. Thanks a lot for providing such an easily understandable code like this.
Bruce Barstow
In the columns section the first sort expression may not be what you had intended. I have a grid view that is dynamically bound to new sources and by removing the xml columns altogether I was able to use your code to auto sort any column. Thank you. This is easier that the convoluted method i came up with.
sumit singh
i want to use sorting when the auto generated column is true.. how to do this please reply
Stephen
This helped me simplify my Sorting methods. Thank you.
kasimacsys
really helpful and understandable.. thanks..
Chandra shekar
Good Work. Keep it !
krishna(tidel park)
i am getting this prob evry time u helped me alot thanx
This is great code.Easily to understand. How can change the color of row when i selected the dropdown item. Example:when i was selected in Delhi in dropdown list all the related row is yellow and when i was select Mumbai the color is green.If you have any idea of this solution please suggest me. Regard's Arun Kaundel
Azeez
Very nice article and neatly explained
Unnati
Thanks, it worked
Tanuj Sharma
Woow,
It's working properlly nice job.
Keep sending this type of accurate codes.
mritunjay kumar
hello .. its working nice ... thanks
Mr JJ
You are awesome! I'll give you all stars for saving my time on doing my GridView sorting for whole day. Thanks and you are the best!
prasad
its good ..but which way to connect the data to the database....
plese help me
Valmir
It's working thanks...
Fedor
YAHOO!!! The best info about sorting in asp.net that I've seen ever.
shilpa agrawal
This site is very useful and it have the best code about gridview.I am impressed so much.Very very thanks for this
dsadsa
very nice.loved it alot
dennis
This is not an efficient code. Not usable in enterprise level. You can not go to the database every time you make sorting! If you are doing a school project, that is OK.
Ezineasp.net
@Dennis, Yes you are true this code is not for enterprise level application. You must use SQL Stored Procedure that takes parameters such as page number, page size, any search criteria based parameter and return the desired results along with the total number of records matching the query. There are different ways for getting paged results such as using Temp table in stored proc, using With clause or cursors etc.
dpa
hi,
Its very useful and easy to undersatnd..

Thank you so much
This code does not work with sorting and paging at the same time. Why? Can any one fix that? It's important when you post some code to make sure that it works for any possible condition like loading, sorting, paging, etc.
Ram Nandan
Good morning and thank you so much for providing a code for gridview sorting which is very easy to understand and deploy.
Can you please let me know how we can sort the gridview control with any single field.

Thanks and Regards.
RamNandan
Krishna Prasad
Really Good Logic and Simple Code technics. :)
Mitesh
I am having trouble in sorting. When first time I click on any column for sorting, It is doing nothing. But when I click again second time on column it does sorting. What is the problem? Can any one tell me? Thanks,
Mithun
ausome code, worked like a breeze, 100/100 marks for u sir, please keep on posting complete and precise code like this, so that begginers can understand the concepts,



thanks a lot sir

warm regards
Mithun
thank u lot of
farima
thank you very much,it was very good and useful.
RANJAN KUMAR SAHOO
thank u so much sir. I am very much happy for ur answer
Ismael
Very Usefull code, Nice Work !!!
Mercy
Gooood... Keep It Up.. ill give u 5 star and munch also:)
Alex
exactly what i am looking for - thank you.
laurent
i have a method more simple in few lines: (code in vb.net, for translation in c# it is easy) Dim SortDirection As String, SortExpression As String SortExpression = e.SortExpression If (SortExpression = ViewState("SortExpression") And ViewState("SortDirection") = "asc") Then SortDirection = "desc" Else SortDirection = "asc" End If ViewState("SortDirection") = SortDirection ViewState("SortExpression") = SortExpression Dim ds As Data.DataSet=refresh() Dim dt As Data.DataTable = ds.Tables(0) '<<<< fill ds with the method refresh() dt.DefaultView.Sort = SortExpression & " " & SortDirection GridView1.DataSource = dt.DefaultView GridView1.DataBind() that's all. it's easy then to place this code in a generic class, to apply to other gridviews there is a lot of complicated solution in the web !!! why do it simple when you can do it complicated ? and your program don't manage the cases when the user change the sort colomun (must restart to "asc")
laurent
i have a method more simple in few lines: (code in vb.net, for translation in c# it is easy) Dim SortDirection As String, SortExpression As String SortExpression = e.SortExpression If (SortExpression = ViewState("SortExpression") And ViewState("SortDirection") = "asc") Then SortDirection = "desc" Else SortDirection = "asc" End If ViewState("SortDirection") = SortDirection ViewState("SortExpression") = SortExpression Dim ds As Data.DataSet=refresh() Dim dt As Data.DataTable = ds.Tables(0) '<<<< fill ds with the method refresh() dt.DefaultView.Sort = SortExpression & " " & SortDirection GridView1.DataSource = dt.DefaultView GridView1.DataBind() that's all. it's easy then to place this code in a generic class, to apply to other gridviews there is a lot of complicated solution in the web !!! why do it simple when you can do it complicated ? and your program don't manage the cases when the user change the sort colomun (must restart to "asc")
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers