.NET (283) administrative (42) Ajax (42) ASP.NET (144) bicycle (2) books (152) browser (7) C# (121) cars (1) chess (25) CodePlex (10) Coma (7) database (37) deployment (3) Entity Framework (2) essay (96) flash/shockwave (2) flex (1) food (3) friend (2) game (14) idea (5) IIS (8) javascript (76) LInQ (2) Linux (6) management (4) manga (35) misc (590) mobile (1) movies (70) MsAccess (1) murder (2) music (62) mysql (1) news (96) permanent (1) personal (58) PHP (1) physics (2) picture (261) places (12) politics (13) programming (462) rant (107) religion (3) science (38) Sharepoint (3) software (53) T4 (2) technology (10) Test Driven Development (4) translation (2) VB (2) video (87) Visual Studio (44) web design (45) Windows API (8) Windows Forms (2) Windows Server (4) WPF/Silverlight (60) XML (10)

Thursday, October 30, 2008

Sorting LInQ results in a GridView

I had this really old site that I was asked to "upgrade". Net 1.1 to 3.5. So I had to change old ADO.Net SqlConnection to Linq-to-Sql. A lot of unforseen issues. Sometimes it is close to impossible to recreate a simple SQL query without changing the database, as in the case of updating tables or views without primary keys.

Anyway, I got stuck in a very simple issue: How to sort a Linq query based on the string returned by the GridView Sorting event. After a lot of tries and Googling I found it was easier to use third party software (although it's more of a 2.5rd party software, as it is made by Scott Guthrie from Microsoft). Here is the link to the blog entry: Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library) . You can find there a sample project to download, with the LINQ Dynamic Library inside.

With this library and the OrderBy extension methods the code becomes:
var somethings=from something in db.Somethings....;
var data = somethings.OrderBy(Sort + " asc");
gv.DataSource=data;
gv.DataBind();

No comments: