Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to Sort Grid View Columns Programmatically

Author: DevASP Team
Download Source Code : 704_DataGrid_DataView.zip

In this article I will try to explain you how you can sort GridView column programmatically using DataView.

During application development many times developer used to face scenarios in which resending the data back to database and apply “ORDER BY” clause and get data back again. Some times this strategy makes the execution slow. In ASP.Net 2.0 we have a DataView “SORT” property that solves this problem easily and effectively. A sample application will provide you the idea that how you can use this property.

 

To begin with this create a new application add a GridView Control. I am assuming that your database is already exists so I am not going into the details of Database procedures. Your .aspx page code will be look like this:

 

<div>

        <asp:GridView ID="GridView1" runat="server">

        </asp:GridView>       

</div>

 

Now in .aspx.cs file add the following code in page load event. You can also create a separate methods or functions but here I am adding all in same event that is on PAGE LOAD event.

 

Create new connection object and add connection string. Fill SqlDataAdapter with result set and using its FILL method add the result set to Data Table new use the following command to sort your result set:

 

        DataView dv = dt.DefaultView;

        dv.Sort = "ENAME";

 

This will sort you ENAME column by default Ascending. Your whole code to execute the basic of DataView sorting is as follows:

 

       SqlConnection sconn = new SqlConnection("User ID=loginid;Password=password;Initial Catalog=DEMODB;Data Source=HOME-EC56DF9512");

 

        sconn.Open();

 

        DataTable dt = new DataTable();

        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM EMP", sconn);

        da.Fill(dt);

 

        DataView dv = dt.DefaultView;

        dv.Sort = "ENAME";

 

        GridView1.DataSource = dv;

        GridView1.DataBind();

 

        sconn.Close();

Article Comments
Excellent Solved my Problem......

Posted on 11/27/2009 7:39:48 AM by Ashish Kalia

nice job.. :D

Posted on 8/11/2010 10:48:57 PM by paul edward

very good....

Posted on 8/16/2010 7:05:26 AM by Vikram

Nice but how to sort Decending order please tell me

Posted on 11/13/2010 6:59:10 AM by Vinoth

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to Display Image in GridView Control Using Property

Disclaimer - Privacy
© 2002-2017 DevASP.net