How to Bind rdlc report using business object? - c#

i have business object called "TeamMaster",
in which i define three properties,Id,Name & Flg.
in my .rdlc report i apply TeamMaster object as a data source,
now i write the following code in page load event of form in which i add report viewer control and i define my report as a local report.
using (RDLC_DEMO_DBEntities objdatabase = new RDLC_DEMO_DBEntities())
{
lstTeamMstr = objdatabase.TeamMasters.ToList();
}
this.TeamMasterBindingSource.DataSource = lstTeamMstr;
this.reportViewer1.RefreshReport();
when i check this code using debugging i get 6 records in TeamBindingSource,
but in windows report only displays six blank rows,
what is the problem?

Follow this code : >>
string path = HttpContext.Current.Server.MapPath(Your Report path);
ReportViewer1.Reset(); //important
ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local;
// Add sub report even handler if you need
***ReportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(MySubreportProcessingEventHandler);***
LocalReport objReport = ReportViewer1.LocalReport;
objReport.ReportPath = path;
// Add Parameter If you need
List<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("Name", Value));
ReportViewer1.LocalReport.SetParameters(parameters);
ReportViewer1.ShowParameterPrompts = false;
ReportViewer1.ShowPromptAreaButton = false;
ReportViewer1.LocalReport.Refresh();
//Add Datasourdce
ReportDataSource reportDataSource = new ReportDataSource();
reportDataSource.Name = "Datasource Name Used due to report design";
reportDataSource.Value = DataSourceValue(Your object data-source);
objReport.DataSources.Add(reportDataSource);
objReport.Refresh();
Here Subreport Even handler code
private void MySubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
{
//You can get parameter from main report
int paramname = int.Parse(e.Parameters[0].Values[0].ToString());
//You can also add parameter in sub report if you need like main report
//Now add sub report data source
e.DataSources.Add(new ReportDataSource("DataSource Name",DataSourceValue)));
}
If you need to create Drillthrough report than follow this link Click here for Drillthrough report

Related

How to pass multiple parameters to Crystal Reports using C#?

I used this code to pass a parameter to Crystal Reports, but I can't pass multiple parameters. How can I change this code to pass multiple parameters from C# to Crystal Reports?
this.Cursor = Cursors.WaitCursor;
RPT.RPT_Sale_by_day report = new RPT.RPT_Sale_by_day();
RPT.Form_RPT frm = new RPT.Form_RPT();
report.SetParameterValue("#date1", dt_num1.Value);
frm.crystalReportViewer1.ReportSource = report;
frm.ShowDialog();
this.Cursor = Cursors.Default;
//Initiating created Crystal Report
ParameterValues Params =new ParameterValues(); // Creating collection of parameters
ParameterDiscreteValue Par_Ref =new ParameterDiscreteValue(); // Discrete parameter that comes from SP and shows on Crystal Report
String PARAMETER1_VALUE ="123";
String PARAMETER2_VALUE = "ABC";
Params.Clear(); // Cleaning data collection
Par_Ref.Value = PARAMETER1_VALUE; // Assigning discrete value to our variable
Params.Add(Par_Ref); //Adding discrete parameter to parameter collection
report.DataDefinition.ParameterFields["PARAMETER1_NAME"].ApplyCurrentValues(Params); //Applying values from our collection to Crystal Report parameters
Params.Clear();
Par_Ref.Value = PARAMETER2_VALUE;
Params.Add(Par_Ref);
report.DataDefinition.ParameterFields["PARAMETER2_NAME"].ApplyCurrentValues(Params);

How do you pass data source to a local report when you use Navigation-> Go to report?

We are moving from Reporting Services remote to local,for this i've been converting the rdl files to rdlc successfully and changing the reportviewers to local processing and passing the data source via code like this:
ReportDataSource data = new ReportDataSource("PARAGAINSA", new InventarioRptCs().Selecciona_Saldos_Articulo(locid,
BodId,depid,FamId,NBid,imId,desde,hasta));
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(data);
ReportViewer1.LocalReport.Refresh();
Works great, i've also encounter some reports that have some subreports to pass the data source to the sub reports i've been doing it like this:
ReportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubReporteHandler);
private void SubReporteHandler(object sender, SubreportProcessingEventArgs e)
{
int im_id = Convert.ToInt32(e.Parameters[1].Values[0].ToString());
int loc_id = Convert.ToInt32(e.Parameters[0].Values[0]);
e.DataSources.Add(new ReportDataSource("PARAGAINSA", new InventarioRptCs().Selecciona_Saldos_Articulo_Det(loc_id,im_id)));
}
it also worked great, so i happily continue until i find a Report that has a subreport and the subreport has this in one of the fields:
when i click on the field that acts as the navigation link to the other report i get this
A data source instance has not been supplied for the data source 'datasource'.
so my question is: is there anyway i can pass the data source to the report inside the sub report that is been call via navigation -> go to report? if so how?
I am using VS 2013, with SQL server 2012
Thank you for reading, pardon my english not my first languague
Since i was not able to find another way to solve this i did the following to try and simulate the navigation between reports that is only available(to my knowledge) in processing mode remote,
First in the rdlc file i added 'Ver mas informacion' in the title property of the column that was acting as the link to the other report and set the Color to blue to give it a link style
i had to add the tooltip(rendes to title attribute) because i was not able to find another way to be able to select those specific cells that i wanted
then a css style to set the Cursor to pointer
[title="Ver mas informacion"] {
cursor:pointer;
}
then a script using jquery to handle the click event geting the values that i need as a parameter to the other report, navigate to the other report and pass the parameter via URL
$(window).load(function () {
$(document).on('click', '[title="Ver mas informacion"]', function () {
var locId = $('[id$="ddLocal"]').val();
var Fecha = $(this).parent().parent()[0].childNodes[2].childNodes[0].innerHTML;
var TT_Id = $(this).parent().parent()[0].childNodes[9].childNodes[0].innerHTML;
var Ap_Id = $(this).parent().parent()[0].childNodes[10].childNodes[0].innerHTML;
window.open(window.location.origin + config.base + '/Reportes/RptSubViewer.aspx?Sub=Doc&Loc=' + locId + '&Fecha=' + Fecha + '&AP=' + Ap_Id + '&TT_Id=' + TT_Id);
});
});
then over the other webform i only added a reportviewer and on the code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["Sub"] == "Doc")
{
string _loc = Request.QueryString["Loc"];
string _fecha = Request.QueryString["Fecha"];
string _Ap_Id = Request.QueryString["AP"];
string _TT_Id = Request.QueryString["TT_Id"];
int loc_id = 0, TT_id = 0, Ap_Id = 0;
CultureInfo provider = new CultureInfo("en-US");
DateTime Fecha = DateTime.Now;
if (!string.IsNullOrEmpty(_loc))
loc_id = Convert.ToInt32(_loc);
if (!string.IsNullOrEmpty(_fecha))
Fecha = DateTime.ParseExact(_fecha,"dd/MMM/yyyy",provider);
if (!string.IsNullOrEmpty(_Ap_Id))
Ap_Id = Convert.ToInt32(_Ap_Id);
if (!string.IsNullOrEmpty(_TT_Id))
TT_id = Convert.ToInt32(_TT_Id);
if (TT_id == 14 || TT_id == 15 || TT_id == 21)
{
List<ReportParameter> paramList = new List<ReportParameter>();
paramList.Add(new ReportParameter("LocId", _loc));
paramList.Add(new ReportParameter("Fecha", Fecha.ToShortDateString()));
paramList.Add(new ReportParameter("TT_Id", _TT_Id));
paramList.Add(new ReportParameter("TT_Doc", _Ap_Id));
ReportDataSource data = new ReportDataSource("ARACLDS", new InventarioRptCs().Selecciona_Saldos_Articulo_Doc(loc_id, Fecha, TT_id, Ap_Id).ToList());
RVSubNav.LocalReport.ReportPath = "Rdlcs\\ReporteKardexDoc.rdlc";
RVSubNav.Visible = true;
RVSubNav.LocalReport.SetParameters(paramList);
RVSubNav.LocalReport.DataSources.Clear();
RVSubNav.LocalReport.DataSources.Add(data);
RVSubNav.LocalReport.Refresh();
}
}
}
}
not sure if the best way but it got the job done

.RDLC Report 2008 (in VS 2010) ReportViewer appears with no report or data

Working with .RDLC 2005 in VS 2008 this technique worked very well, now in .RDLC 2008 as implemented in VS 2010 I get a blank (or no?) report.
I have made a couple of changes to accommodate .RDLC 2008 and at this time I am getting no exceptions. The present (not desired) output looks like:
I have a custom ReportController class that has a public method to ShowReport (also one to manage the exporting of reports, but that is not (yet) in play.)
From the asp.net page I invoke the controller in the property set (of Type DataSet, invoked by the page controller) like: (ReportController implements IDisposable)
try
{
using (var reportController = new ReportController(true))
{
_ReportViewer = reportController.ShowReport("DemonstrationList", value, phReportHolder);
if (_ReportViewer != null)
{
_ReportViewer.ShowRefreshButton = false;
_ReportViewer.ShowPrintButton = false;
_ReportViewer.Width = Unit.Pixel(700);// Unit.Percentage(99);
_ReportViewer.Height = Unit.Pixel(700);// Unit.Percentage(90);
}
}
lblRecordCount.InnerText = value.Tables[0].Rows.Count.ToString();
}
catch (Exception ex)
{
phReportHolder.InnerHtml = string.Format("There was an error attempting to process this report <br/><br/><div style='color:White;'>{0}</div>", ex.Message);
}
and the ShowReport method is:
public ReportViewer ShowReport(string ReportName, DataSet ds, HtmlContainerControl ReportContainer)
{
ReportContainer.Controls.Clear();
ReportViewer reportViewer = BuildReport(ReportName, ds);
ReportContainer.Controls.Add(reportViewer);
return reportViewer;
}
This allows me to tell the controller to put any 'valid' report into any htmlcontainercontrol using any provided dataset.
BuildReport takes the data and the report name and builds the report as:
private ReportViewer BuildReport(string ReportName, DataSet ds)
{
try
{
_activeDS = ds;
string ReportFileName = ResolveRDLCName(ReportName);
// ResolveRDLCName is used along with path strings
// initialized from configuration settings in the
// constructor to make this portable.
var viewer = new ReportViewer();
viewer.ProcessingMode = ProcessingMode.Local;
viewer.LocalReport.ReportPath = ReportFileName;
viewer.LocalReport.DisplayName = ReportName;
viewer.LocalReport.EnableHyperlinks = true;
AssignReportData(ds, viewer.LocalReport);
return viewer;
}
//...Exception handlers below are not invoked at this time
And 'AssignReportData' attaches the data to the report.
private static void AssignReportData(DataSet ds, LocalReport Report)
{
var listOfDatasources = Report.GetDataSourceNames();
foreach (string dsn in listOfDatasources)
{
ReportDataSource rds = new ReportDataSource(dsn,ds.Tables[dsn]);
Report.DataSources.Add(rds);
}
}
Development techniques ensure that dataTable/dataSource names stay in agreement (and if they were not I would get a specific exception, which I do not.)
I was having a similar problem which this blog post answered. Short answer is I needed to install the report viewer redistributable, and add the handler.
It seems like the report content gets rendered but is simply not visible.
Try to look at the generated HTML (DOM) with
Chrome: right-click on the report area, "Inspect Element" to explore the DOM
Internet Explorer: install the IE Developer Toolbar to explore the DOM
Maybe some CSS that has worked in the past now hides your report area.

Unable to display report in ASP.Net page

I have created a dataset and using it in my crystal report. Issue is that at design time i am able to display the data but when I execute it using ASP.Net page its showing a blank page. Below is my code that i am using to display the report programatically:
/// <summary>
/// Displays batch report
/// </summary>
/// <param name="agreementId"></param>
private void ShowStatements(string agreementId)
{
var crvStatements = new CrystalReportViewer();
var reportDocument = new ReportDocument();
reportDocument.Load(Server.MapPath("Statements.rpt"));
crvStatements.ReportSource = reportDocument;
var dt1 = new dsStatements.usp_GetBillDetailsByAgreementIdDataTable();
var dt2 = new dsStatements.usp_GetTransactionTypesByAgreementIdForBillDataTable();
var adapter1 = new usp_GetBillDetailsByAgreementIdTableAdapter();
var adapter2 = new usp_GetTransactionTypesByAgreementIdForBillTableAdapter();
adapter1.Fill(dt1, agreementId);
adapter2.Fill(dt2, agreementId);
//var statements = new dsStatements();
//statements.Tables.Add(dt1);
//statements.Tables.Add(dt2);
// reportDocument.SetDataSource(dsStatements);
crvStatements.RefreshReport();
}
Please note that i haven't used any control on the page. I am adding report viewer , report source and dataset programatically. Please help me out. I need it ASAP. I am using VS2010 with CR 2010
Can you provide the reason why you are creating the Crystal Report Viewer at runtime and not simply creating the control on the page? Some people do this so that they can export without displaying, but I don't see any code for that.
I haven't tested this, but I believe the below would work if you had a viewer control on your page.
private void ShowStatements(string agreementId)
{
//var crvStatements = new CrystalReportViewer(); //created on the page
ReportDocument reportDocument = new ReportDocument();
reportDocument.Load(Server.MapPath("Statements.rpt"));
crvStatements.ReportSource = reportDocument;
System.Data.DataTable dt1 = new dsStatements.usp_GetBillDetailsByAgreementIdDataTable();
System.Data.DataTable dt2 = new dsStatements.usp_GetTransactionTypesByAgreementIdForBillDataTable();
System.Data.DataSet statements = new System.Data.DataSet();
statements.Tables.Add(dt1);
statements.Tables.Add(dt2);
reportDocument.SetDataSource(dsStatements);
crvStatements.DataBind();
}
I'm assuming that the report is set up with these tables linked in the report, and you may have to give the datatables a name so that Crystal knows how to map each datatable to the corresponding table within the report. If possible you may try to limit the report to accepting a single table until you have the loading logic worked out.
If each of these datatables represent the data for a subreport then you'll have to iterate through those reports and set the datasources manually.
I hope this helps, but I answered this off the top of my head so there are probably things I've missed. If it doesn't work you just provide a comment and we can probably work through any issues.
The RefreshReport(); makes the Report appearing Empty. try it before loading the Datasets.

Switching DataSources in ReportViewer in WinForms

I have created a winform for the users to view view the many reports I am creating for them. I have a drop down list with the report name which triggers the appropriate fields to display the parameters. Once those are filled, they press Submit and the report appears. This works the first time they hit the screen. They can change the parameters and the ReportViewer works fine. Change to a different report, and the I get the following ReportViewer error:
An error occurred during local report processing.
An error has occurred during the report processing.
A data source instance has not been supplied for the data source "CgTempData_BusMaintenance".
As far as the process I use:
I set reportName (string) the physical RDLC name.
I set the dataSource (string) as the DataSource Name
I fill a generic DataTable with the data for the report to run from.
Make the ReportViewer visible
Set the LocalReport.ReportPath = "Reports\\" = reportName;
Clear the LocalReport.DataSources.Clear()
Add the new LocalReport.DataSources.Add(new ReportDataSource(dataSource, dt));
RefreshReport() on the ReportViewer.
Here is the portion of the code that setups up and displays the ReportViewer:
/// <summary>
/// Builds the report.
/// </summary>
private void BuildReport()
{
DataTable dt = null;
ReportingCG rcg = new ReportingCG();
if (reportName == "GasUsedReport.rdlc")
{
dataSource = "CgTempData_FuelLog";
CgTempData.FuelLogDataTable DtFuelLog = rcg.BuildFuelUsedTable(fromDate, toDate);
dt = DtFuelLog;
}
else if (reportName == "InventoryCost.rdlc")
{
CgTempData.InventoryUsedDataTable DtInventory;
dataSource = "CgTempData_InventoryUsed";
DtInventory = rcg.BuildInventoryUsedTable(fromDate, toDate);
dt = DtInventory;
}
else if (reportName == "VehicleMasterList.rdlc")
{
dataSource = "CgTempData_VehicleMaster";
CgTempData.VehicleMasterDataTable DtVehicleMaster = rcg.BuildVehicleMasterTable();
dt = DtVehicleMaster;
}
else if (reportName == "BusCosts.rdlc")
{
dataSource = "CgTempData_BusMaintenance";
dt = rcg.BuildBusCostsTable(fromDate, toDate);
}
// Setup the DataSource
this.reportViewer1.Visible = true;
this.reportViewer1.LocalReport.ReportPath = "Reports\\" + reportName;
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource(dataSource, dt));
this.reportViewer1.RefreshReport();
}
Any ideas how to remove all of the old remaining data? Do I dispose the object and recreate it?
I figured it out. I needed to add: reportViewer1.Reset(); to the beginning of the method.

Categories