Manually Sorting GridView and List Controls in ASP.NET/C#
You must perform sorting manually when you do not bind your control to your data source declaratively (i.e. with a DataSource control). If you perform binding manual using your own code, this article may be for you.
I know this topic is covered extensively on the web already, however I’ve seen some dodgy implementations and advice where you’re recommended to handle the ViewState directly. Here I introduce a simple helper class that makes manual sorting easier - especially if you have to implement it again and again and again. We’ll use a GridView as an example.
The simple helper class, SortInfo:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MyNamespace { [Serializable()] public class SortInfo { /// <summary> /// The expression to sort by /// </summary> public string SortExpression; /// <summary> /// The direction to search /// </summary> public System.Web.UI.WebControls.SortDirection SortDirection = System.Web.UI.WebControls.SortDirection.Ascending; /// <summary> /// Creates a new SortInfo class with the specified sort expression. /// </summary> public SortInfo(string sortExpression) { SortExpression = sortExpression; } /// <summary> /// Casts from an existing SortInfo instance. If that fails, creates a SortInfo class with the specified sort expression /// </summary> /// <param name="sortInfo">The possibly pre-existing SortInfo instance.</param> /// <param name="defaultSortExpression">The default sort expression.</param> /// <returns></returns> public static SortInfo CastOrDefault(object sortInfo, string defaultSortExpression) { if (sortInfo is SortInfo) return (SortInfo)sortInfo; else return new SortInfo(defaultSortExpression); } /// <summary> /// Updates the SortInfo class with the specified expression. /// </summary> /// <param name="sortExpression"></param> public void Update(string sortExpression) { // same expression? if (sortExpression == SortExpression) { // reverse direction SortDirection = SortDirection == System.Web.UI.WebControls.SortDirection.Ascending ? System.Web.UI.WebControls.SortDirection.Descending : System.Web.UI.WebControls.SortDirection.Ascending; } else { // set expression and default direction SortExpression = sortExpression; SortDirection = System.Web.UI.WebControls.SortDirection.Ascending; } } } }
First you must create an instance of this SortInfo on your page. Declare it at class level as so:
protected SortInfo MySortInfo;
Then you must pull it from the ViewState, or create it with the default sorting. This is done in one line as follows:
ViewState["MySortInfo"] = MySortInfo = SortInfo.CastOrDefault(ViewState["MySortInfo"], "DefaultColumnName");
To enable sorting on the GridView, enable the property AllowSorting. Then for each column you want sorted, set the SortExpression field. I typically keep the SortExpression field the same as the corresponding database column or the column header text.
To handle the sorting, implement the Sorting event of the Gridview. In this event, you update your SortInfo class and refetch/rebind the data. This will look something like this:
protected void gdvClients_Sorting(object sender, GridViewSortEventArgs e) { MySortInfo.Update(e.SortExpression); BindGridview(); }
Finally, you put all your fetching/binding code into BindGridview(). You might also be calling BindGridview() in your Page_Load if it’s not a post-back, but that depends on your circumstances. Your BindGridview function should fetch the data from your datasource, sort it based on MySortInfo, and then bind it to your gridview. Using LINQ, this looks something like this:
protected void BindGridview() { // the datasource var ctx = MyDataSource; // get data from datasource IEnumerable<MyDatatype> myData = ctx.MyData.Where(d => d.SomeCondition); // sort data if (MySortInfo.SortExpression == "FirstName") myData = myData.OrderBy(s => s.FirstName); else if (MySortInfo.SortExpression == "LastName") myData = myData.OrderBy(s => s.LastName); else if (MySortInfo.SortExpression == "Age") myData = myData.OrderBy(s => s.Age); // if descending, reverse data if (MySortInfo.SortDirection == SortDirection.Descending) myData = myData.Reverse(); // bind gdvClients.DataSource = sorted; gdvClients.DataBind(); }
And that’s it. Using this method, you abstract most of the storing, retrieving and handling of the sorting information and focus mainly on the code to perform the sorting.
Hope you found this helpful.
~
3 Comments to Manually Sorting GridView and List Controls in ASP.NET/C#
Also, if you get an error when you try to call .Reverse(), chuck your results in a list first with .ToList().
Pillspot.org. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices(up to 40% off average US price).Pillspot.org. Herbal-supplements@buy.online” rel=”nofollow”>.< /a …
Categories: Cholesterol.Weight Loss.General Health.Stop SmokingVitamins/Herbal Supplements.Antibiotics.Skin Care.Antiviral.Eye Care.Antidiabetic.Anti-allergic/Asthma.Pain Relief.Womens Health.Blood Pressure/Heart.Anxiety/Sleep Aid.Antidepressants….
Buy:Cialis.Cialis Super Active+.Tramadol.Soma.Levitra.Viagra.Viagra Super Active+.Propecia.VPXL.Viagra Super Force.Cialis Soft Tabs.Super Active ED Pack.Viagra Professional.Viagra Soft Tabs.Zithromax.Maxaman.Cialis Professional….
February 28, 2010