Using ASP.Net C# DataTable DefaultView Sort Rows

Updated on 20 Aug 2012,
Published on 06 Sep 2008

In ASP.Net C#, DefaultView.Sort property of DataTable provides the functionality to sort the customized table view generated by the associated property of DataView class i.e. DefaultView property. It allows you to pass the sort expression similar to order by clause of SQL query. You just need to pass the column Name and sort direction to sort the rows of DataTable. When DefaultView.Sort property is used over the ASP.Net DataTable object, it customizes the view of DataTable within the same memory allocated to the instance of DataTable based on the sort expression. Consider the same C# sample code that we used in the previous tutorial: ASP.Net DataTable Select rows using DefaultView RowFilter to understand the use of Sort property.

C# Code for ASP.Net DataTable DefaultView Sort Rows

myDataTable.DefaultView.RowFilter = "unit_price < 40"; 

myDataTable.DefaultView.Sort = "unit_price desc"; 

GridView1.DataSource = myDataTable;

You can use both properties of DefaultView property of DataTable to sort the filtered rows. Or you can use one of them to Sort all the rows present in the DataTable. Above code will generate the following output:

Continue to next tutorial: ASP.Net C# Convert DataSet to ArrayList to learn how to convert dataset records into ArrayList using C# code.

6 Responses to "Using ASP.Net C# DataTable DefaultView Sort Rows"
How will be the best way to cancel the sorting.
What i mean is how can i return to the original state of the grid viewe, showing all the rows
Hi Luisfer

You can simply set the Sort string as empty string e.g.:

datatable.DefaultView.Sort = "";
Could you explain why with 100000 row it takes so long? I know that there are a lot of rows but could you explain a little bit
Thank you Your post is Helpful to me...
hey when i was sorting with 1,2,3,4,11,12,13,23,24,25 it was sorting like 1,11,12,13,2,23,24,25,3 can you please help me...............
@Ravi It shows this type of behavior if the data table column is of string type. Please check the data type of column containing these values. Make sure its of integer type. Hope this will do! ;-)
Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email