Category / Section
How to sort the pivot item with DateTime format
1 min read
In our pivot grid, you can able to sort the column based on the dates by setting Comparer for the specific Pivot Item. This can be achieved by writing Comparer for the Pivot Item which has “DateTime” field as FieldMappingName, so that it gets sorted based on the chronological order.
C#
public class DateComparer : IComparer { Dictionary<string, int> lookUp = null; string fmt = string.Empty; public DateComparer(string format) { fmt = string.Format("{0}", format); lookUp = new Dictionary<string, int>(); DateTime dt0 = Convert.ToDateTime("2013/12/01"); DateTime dt1 = Convert.ToDateTime("2014/01/08"); double days = (dt1 - dt0).TotalDays; for (int j = 0; j <= days; j++) { DateTime dt = dt0.AddDays(j); if (!lookUp.ContainsKey(dt.ToString(fmt))) { lookUp.Add(dt.ToString(fmt), j); } } } public int Compare(object x, object y) { DateTime x1, y1; if (DateTime.TryParse(x.ToString(), out x1) && DateTime.TryParse(y.ToString(), out y1)) { x = x1.ToString(fmt); y = y1.ToString(fmt); } return lookUp[x.ToString()].CompareTo(lookUp[(y.ToString())]); } }
Figure: Pivot column with DateTime format appears in chronological order