I have the following bit of code in multiple places in my app:
var subReport = new XRptEventHeader();
var eventHeaderList = FreqReports.GetEventHeaderList(studyPK);
var dataSourceSubReport = (XRSubreport)oRpt.FindControl("xrSubreportSite", false);
dataSourceSubReport.ReportSource = subReport;
dataSourceSubReport.ReportSource.DataSource = eventHeaderList;
It is used in multiple places where the type for oRpt
differs. I tried to use a generic something like this
public static T SetEventHeader<T>(T oRpt , Guid studyPK)
{
var subReport = new XRptEventHeader();
var eventHeaderList = FreqReports.GetEventHeaderList(studyPK);
var dataSourceSubReport = (XtraReport)oRpt.FindControl("xrSubreportSite", false);
dataSourceSubReport.ReportSource = subReport;
dataSourceSubReport.ReportSource.DataSource = eventHeaderList;
return oRpt;
}
But when I get to the line
var dataSourceSubReport = (XtraReport)oRpt.FindControl("xrSubreportSite", false);
and oRpt
it doesn't have the FindControl
function even when I cast with the base class of each class.
Does anyone have any suggestions on how I could get this to work?
CodePudding user response:
What you need to do is restrict the value of T
to a base class or interface that all your oRpt
s share. You do this by adding a "generic constraint".
In your case I suspect you are writing a website, and so the base class of all your oRpt
s can be System.Web.UI.Control. If you are not, then work out an appropriate base type (class or interface) for your particular needs.
public static T SetEventHeader<T>(T oRpt , Guid studyPK)
// Add a "generic constraint" to ensure T is a Control.
where T : System.Web.UI.Control
{
var subReport = new XRptEventHeader();
var eventHeaderList = FreqReports.GetEventHeaderList(studyPK);
var dataSourceSubReport = (XtraReport)oRpt.FindControl("xrSubreportSite", false);
dataSourceSubReport.ReportSource = subReport;
dataSourceSubReport.ReportSource.DataSource = eventHeaderList;
return oRpt;
}
CodePudding user response:
Thanks to RB as they gave me the information I needed. It also made me realize I needed to cast something else and try/catch for if the section didn't exist for some reason. Here is the final code that worked:
public static T SetEventHeader<T>(T oRpt, Guid studyPK)
where T : XtraReport
{
try
{
XRSubreport dataSourceSubReport = oRpt.FindControl("xrSubreportSite", false) as XRSubreport;
var subReport = new XRptEventHeader();
var eventHeaderList = FreqReports.GetEventHeaderList(studyPK);
dataSourceSubReport.ReportSource = subReport;
dataSourceSubReport.ReportSource.DataSource = eventHeaderList;
return oRpt;
}
catch (Exception ex)
{
return oRpt; //subsection not present
}
}