Symptom
- A report contains existing sort.
- How to remove the existin sort and replace it with new sort fields?
Environment
- SAP Crystal Reports, Developer Version for Visual Studio .NET
- Visual Studio .NET, 2010 / 2012 / 2013
Resolution
- Use the following code:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.ReportAppServer.ClientDoc;
using CrystalDecisions.ReportAppServer.Controllers;
using CrRas= CrystalDecisions.ReportAppServer.DataDefModel;
public static void ReportSorting(ReportDocument rd, List<ReportSortingGrouping> sortByParams, bool resetSorting)
{
if (sortByParams != null && sortByParams.Count > 0)
{
ISCDReportClientDocument rcd = rd.ReportClientDocument;
DataDefController dataDefController = rcd.DataDefController;
CrRas.Sorts sorts = dataDefController.DataDefinition.Sorts;
SortController sController = dataDefController.SortController;
//First of all remove all those 'RecordSortField' sorting that are in the report otherwise there will be conflict
int sIndex = 0;
foreach (SortField sField in rd.DataDefinition.SortFields)
{
if (sField.SortType == SortFieldType.RecordSortField)
{
CrRas.Sort sort = (CrRas.Sort)sorts[sIndex];
sController.Remove(sort);
sIndex--;
}
sIndex++;
}
//Add new sorting
CrRas.Fields resultFields = dataDefController.DataDefinition.FormulaFields;
foreach (ReportSortingGrouping item in sortByParams)
{
CrRas.Field sortField = (CrRas.Field)resultFields.FindField("{@" + item.FieldName + "}", CrRas.CrFieldDisplayNameTypeEnum.crFieldDisplayNameFormula, CrRas.CeLocale.ceLocaleEnglishUS);
SortController sortController = dataDefController.SortController;
if (sortController.CanSortOn(sortField))
{
CrRas.Sort newSort = new CrRas.SortClass();
newSort.SortField = sortField;
newSort.Direction = item.SortDirection == CrystalDecisions.Shared.SortDirection.AscendingOrder ? CrRas.CrSortDirectionEnum.crSortDirectionAscendingOrder : CrRas.CrSortDirectionEnum.crSortDirectionDescendingOrder;
int index = rd.DataDefinition.SortFields.Count;
sortController.Add(index, newSort);
}
}
}
}
//This class isn't needed if you have different way of doing it.
public class ReportSortingGrouping
{
public int Index { get; set; }
public string FieldName { get; set; }
public SortDirection SortDirection { get; set; }
public string NewFieldName { get; set; }
}
Keywords
crvs cr4vs inproc api code , KBA , BI-DEV-NET-SDK , .NET SDK / COM SDK , How To
Product
SAP Crystal Reports, developer version for Microsoft Visual Studio