Sorting Crystal Reports programmatically

  • Thread starter Thread starter Peter Afonin
  • Start date Start date
P

Peter Afonin

Hello,

I'm still learning Crystal reports, and now I need to sort report
programmatically. I've found a good article about it:
http://blogs.ittoolbox.com/c/coding...elds-in-crystal-report-programmatically-16201.
This is how it described there:

ReportDocument objReport = new ReportDocument();
objReport.Load("Your report path");
FieldDefinition FieldDef;
FieldDef = objReport .Database.Tables[0].Fields[sortField];
objReport.DataDefinition.SortFields[0].Field = FieldDef;
objReport.DataDefinition.SortFields[0].SortDirection =
CrystalDecisions.Shared.SortDirection.DescendingOrder;

When I try to do this, I'm getting an error on this line:

objReport.DataDefinition.SortFields[0].Field = FieldDef;

Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))

This error is also described in this article:

"This is because you didn't define any sort field in your crytal report...
so if you try to add a FieldDef to the SortFields at a specified index and
that index doesn't exist then you will get the error..."

But there is no explanation how to define the sort fields in the report.
I've searched the Google and found several posts about the same issue, but
also no explanation.

So how can I define the sort fields for the report so I could sort
programmatically?

I would appreciate your help.

Thank you,

Peter
 
I had solved this problem myself in a weird way, but it worked.

In a report designer, I'd added one Group field (doesn't matter which one),
and suppressed it, so it's not visible. Somehow this solved the issue, now I
can sort programmatically by any field.

Another strange thing I've noticed - when I pass a sorting order as a
parameter to the report, it actually sorts the report in the opposite
direction, so I had to swap the order:

if (sortDir==CrystalDecisions.Shared.SortDirection.AscendingOrder)
{
sortDir = CrystalDecisions.Shared.SortDirection.DescendingOrder;
}
else
{
sortDir = CrystalDecisions.Shared.SortDirection.AscendingOrder;
}
reportsObjectReport.DataDefinition.SortFields[0].SortDirection = sortDir;

Peter Afonin
 
I love you Peter Afonin!!!! I've been looking how to solve this problem for days!!! and that worked!!! I´m forever grateful!
 
Back
Top