Search code examples
c#exceptiondevexpresssubreportxtrareport

DevExpress XtraReport Master-detail subreport exception when pass parameter from main report


I studying make a sub report by DevExpress 14.1.4

I have XtraReport1, binded it with Orders table XtraReport2, binded it with OrderDetails table XtraReport2 have parameter oID, filer details by order

In the beforePrint event of XtraReport1, I did like the tutorial:

private void xrLabel1_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            int n = Convert.ToInt32(GetCurrentColumnValue("MaKhoa"));
            ((XtraReport2)((XRSubreport)sender).ReportSource).MK.Value = n;
        }

but its throw

An unhandled exception of type 'System.InvalidCastException' occurred in WindowsFormsApplication1.exe

Additional information: Unable to cast object of type 'DevExpress.XtraReports.UI.XRLabel' to type 'DevExpress.XtraReports.UI.XRSubreport'.

Solution

  • Reason:
    You have handled wrong control's BeforePrint event. You are handling xrLable1 event so the sender will be a XRLabel and you are trying to cast it to XRSubReport, So you are getting this error:

    private void xrLabel1_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
    {
        int n = Convert.ToInt32(GetCurrentColumnValue("MaKhoa"));
        ((XtraReport2)((XRSubreport)sender).ReportSource).MK.Value = n; // you have error here
    }
    

    You should handle SubReport BeforePrint event to set value, check the below code snippet:

    using System.Drawing.Printing;
    // ... 
    
    private void xrSubreport1_BeforePrint(object sender, PrintEventArgs e) {
        ((XtraReport2)((XRSubreport)sender).ReportSource).CatID.Value = 
            Convert.ToInt32(GetCurrentColumnValue("CategoryID"));
    }
    

    I suggest you to follow the below documentation links to make Master-Detail Report correctly:
    Master-Detail Report
    How to: Create a Master-Detail Report using Subreports
    Lesson 3 - Create a Master-Detail Report