Search   Articles   Dev Forums   Personalize   Favorites   Member Login   ASP.Net Hosting
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Sunday, February 19, 2006

Search Directory
Trusted by over 7 million customers!
ASP.NET
VB.Net
C-Sharp
SQL Server
 
More Partners >>

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();



Disclaimer - Privacy
Copyright © 2008 DevASP.net