SpellCoder

Welcome to SpellCoder Sign in | Join | Help
in Search

Beckham

Sorting a Grid View That's bounded to IEnumerable

Have you ever had a grid view that's bounded to an IEnumerable collection? Yes.
Very well have you ever wanted to enable sorting to this grid view? Yeah, what's the big deal?

 Okay, here is the deal:-

Grid view enable automatic sorting that allows you to sort you data in the grid view without writing any code but sadly this automatic sorting is enabled only for Grid View that's bounded to a DataSourceControl (i.e. SqlDataSource, ObjectDataSource).
You can't do that with grid view that's bounded to an IEnumerable collection, why?
Because actually the grid view uses the DataSourceControl to sort the data for it.

 So how can I sort my gridview that's bounded to a IEnumerable collection? You can reconstruct your collection as a table and then pass that table to a data view and sort these data using that data view sorting and then bind your grid view to the data view like that :->



This is the defenition of our customer class that will be used to fill our collection.
Notic: The serializable attribute only so we can save our list of cutomers to the ViewState.



We will need to keep track of our current sort expression and direction so we can use it later in resorting the list.



Her we fill our list of customers with some dummy data.

 



Change the sort direction from Ascending to Descending and vice versa.




Look at our Sorting event handler see how much code we wrote to get this done. Is this the only way to do that ?? Noooo, we can do that very easily using LINQ without creating a table or a data view.

LINQ To The Rescue:-
See all that code we wrote to create a table and fill the table with data and then creating the creating the data view, well we don't need all of that.
We will use the Order by extension method to sort our IEnumerable collection.
ex: -  

 



Well that's great and everything but dude you hard coded the sort expression "customer.Id" what will I do if the user clicks on the Name column? Well you can continue hard coding and write an order by statement for each column you have and select the appropriate statement using switch case based on the user's selections.
 Dude that's horrible I don't like hard coding, Is there anyway else like passing the property name as a variable? Well, No you can't pass the property name as a variable but yes there is another way,  You can use reflection to get the property name dynamically ;)


 



Here is our Sorting event handler after using Orderby and reflection :-



Beckham
Published Saturday, March 22, 2008 9:39 AM by beckham
Filed Under: ,
Attachment(s): testGridViewSorting.zip

Comments

No Comments
Anonymous comments are disabled

This Blog

Post Calendar

<March 2008>
SuMoTuWeThFrSa
2425262728291
2345678
9101112131415
16171819202122
23242526272829
303112345

Syndication