RDLC Subreport can no show - c#

I am working with RDLC reports and currently I have a sub report with its properties and parameters within a main report. After trying to generate the report, the below error is shown at the UI :
"Data retrieval failed for the subreport, 'Subreport1', located at: [C:/filepath]"
There is nothing error shown at Visual studio, so I thing the error may not cause by the code.
I think the error comes from the parameters at rdlc not being able to pass into the sub report via the main report . Below is my code:
public ReportViewer Main_Report(string path, ProgressReportFilter item, DataTable dt)
{
ReportViewer reportViewer = new ReportViewer();
try
{
var user = UserAccess.GetCurrentUser();
reportViewer.ProcessingMode = ProcessingMode.Local;
//reportViewer.LocalReport.ReportPath = #"Reports/Main_Report.rdlc";
reportViewer.LocalReport.ReportPath = path;
reportViewer.SizeToReportContent = true;
reportViewer.Width = Unit.Percentage(100);
reportViewer.Width = Unit.Percentage(100);
reportViewer.LocalReport.SetParameters(new Microsoft.Reporting.WebForms.ReportParameter("Year", item.yyyy));
reportViewer.LocalReport.SetParameters(new
Microsoft.Reporting.WebForms.ReportParameter("Month", item.mm));
ReportDataSource ds = new ReportDataSource("Main_DataSet", dt);
reportViewer.LocalReport.DataSources.Add(ds);
reportViewer.LocalReport.SubreportProcessing += new
SubreportProcessingEventHandler(Detail_Alco);
reportViewer.LocalReport.Refresh();
}
catch (Exception e)
{}
return reportViewer;
}
void Detail_Alco(object sender, SubreportProcessingEventArgs e)
{
Helper.log.Info("para is " + e.Parameters[0].Values[0]);
string serial = e.Parameters["serial"].Values[0].ToString();
//Helper.log.Info("serial is " + serial);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("#serial", serial);
string spName1 = "SP_Report_MRS_Detail_Breakdown_Report_Sub_Alco";
SUSDB susdb = new SUSDB();
DataTable dtAlco = ReportHelp.ToDataTable(susdb.DetailBreakdownReport_SubReport_Alco(spName1, parameters));
ReportDataSource ds = new ReportDataSource("Detail_Breakdown_Alco", dtAlco);
e.DataSources.Add(ds);
}
Any help would be appreciated, many thanks

Related

Crystal Reports for Visual Studio 2017 - Exporting a Report

I am creating a c# application to export reports using existing crystal report documents. I have been successful, except for specific instance. When exporting to a file (PDF, xls) I am getting a windows folder dialog to name and locate the export (even though I am defining the format type, location, and name of the file. Is there a way to preclude this windows folder dialog from showing up, and just deposit the export in the described location. Below is the code which is exporting the crystal report. Any help would be greatly appreciated.
static void Main(string[] args)
{
ReportDocument myReportDocument = new ReportDocument();
CrystalReport1 rpt = new CrystalReport1();
CrystalReportViewer cView = new CrystalReportViewer();
ExportOptions crExportOptions = new ExportOptions();
PdfFormatOptions crFormatTypeOptions = new PdfFormatOptions();
DiskFileDestinationOptions crDiskFileDestinationOptions = ExportOptions.CreateDiskFileDestinationOptions();
myReportDocument.Load(args[1]);
myReportDocument.DataSourceConnections[0].SetConnection(args[5], args[5], "Admin", "");
myReportDocument.SetParameterValue(rpt.Parameter_ADDTransformerID.ParameterFieldName.ToString(), args[2]);
myReportDocument.SetParameterValue(rpt.Parameter_ProjectName.ParameterFieldName.ToString(), args[3]);
crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
crDiskFileDestinationOptions.DiskFileName = args[4];
crExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
crExportOptions.ExportDestinationOptions = crDiskFileDestinationOptions;
cView.ReportSource = myReportDocument;
switch (args[0])
{
case "0" :
cView.PrintReport();
break;
case "1" :
cView.PrintReport();
break;
case "2" :
cView.ExportReport();
break;
}
You're creating a new ExportOptions-object instead of assigning the options to the actual ReportDocument-object.
Changing this line
ExportOptions crExportOptions = new ExportOptions();
to
ExportOptions crExportOptions = myReportDocument.ExportOptions;
should work.

Multiple Report (Report will be same but Data/Calculation will be different) in a single RDLC report viewer

I need to show BULK of reports in a single RDLC report viewer. I generated single report using RDLC report with dynamic images. But now I need to generate same report but in multiple numbers where data/calculation will be different. Code for single report generate is given below.
rdlcTax.Visible = true;
rdlcTax.Reset();
rdlcTax.ProcessingMode = ProcessingMode.Local;
rdlcTax.LocalReport.DisplayName = "Tax" + dt.Rows[0]["NAME"].ToString();
rdlcTax.LocalReport.ReportPath = "Reports/rdlcTaxCertificate.rdlc";
ReportDataSource rds = new ReportDataSource("dsTaxCertificate", dt);
var param = new ReportParameter[] {
new ReportParameter("fromDate", fromMonth.Replace("-", " ")),
new ReportParameter("toDate", toMonth.Replace("-", " ")),
new ReportParameter("rateOfDeduction", rateOfDeduction + "%"),
new ReportParameter("name", name),
new ReportParameter("address", address),
new ReportParameter("refNo", refNo),
new ReportParameter("issueDate", issueDate),
new ReportParameter("amount", tdsSum.ToString("N", CultureInfo.InvariantCulture).Split('.')[0]),
new ReportParameter("amountWord", textInfo.ToTitleCase(int.Parse(tdsSum.ToString()).ToText()) + " Taka Only"),
new ReportParameter("imagePath", imagePath, true)
};
rdlcTax.LocalReport.EnableExternalImages = true;
rdlcTax.LocalReport.SetParameters(param);
rdlcTax.LocalReport.DataSources.Clear();
rdlcTax.LocalReport.DataSources.Add(rds);
rdlcTax.DataBind();
rdlcTax.LocalReport.Refresh();
I also tried loop for generate multiple report in same report viewer, but did not work. Report shows only data from last DataTable. Codes are given below.
rdlcTax.Visible = true;
rdlcTax.Reset();
rdlcTax.ProcessingMode = ProcessingMode.Local;
rdlcTax.LocalReport.DisplayName = "Tax Certificate";
rdlcTax.LocalReport.ReportPath = "Reports/rdlcTaxCertificateBulk.rdlc";
rdlcTax.LocalReport.EnableExternalImages = true;
rdlcTax.LocalReport.DataSources.Clear();
foreach (DataTable dt in ds.Tables)
{
var name = dt.Rows[0]["NAME"].ToString();
var address = dt.Rows[0]["ADDRESS"].ToString();
var refNo = dt.Rows[0]["REFERENCE_NO"].ToString();
var issueDate = dt.Rows[0]["ISSUE_DATE"].ToString();
var tdsSum = Math.Round(double.Parse(dt.Compute("Sum(TDS_AMOUNT)", "").ToString()));
ReportDataSource rds = new ReportDataSource("dsTaxCertificate", dt);
var param = new ReportParameter[] {
new ReportParameter("fromDate", fromMonth.Replace("-", " ")),
new ReportParameter("toDate", toMonth.Replace("-", " ")),
new ReportParameter("rateOfDeduction", rateOfDeduction + "%"),
new ReportParameter("name", name),
new ReportParameter("address", address),
new ReportParameter("refNo", refNo),
new ReportParameter("issueDate", issueDate),
new ReportParameter("amount", tdsSum.ToString("N", CultureInfo.InvariantCulture).Split('.')[0]),
new ReportParameter("amountWord", textInfo.ToTitleCase(int.Parse(tdsSum.ToString()).ToText()) + " Taka Only"),
new ReportParameter("imagePath", imagePath, true)
};
rdlcTax.LocalReport.SetParameters(param);
rdlcTax.LocalReport.DataSources.Clear();
rdlcTax.LocalReport.DataSources.Add(rds);
rdlcTax.DataBind();
rdlcTax.LocalReport.Refresh();
}
In code where I have to modify to generate multiple report?
What the purpose of having parameter in your bulk report? This is based on your code snippet like to understand the requirement.
Is all columns names are same in your Tables?
foreach (DataTable dt in ds.Tables)
{
****
}

Create xtrareport with xml in asp.net

I am trying to create a xtrareport with xml in asp.net using c#. I created xml and reference to xtrareport. I have also selected data source schmema and data member on xtrareport design and put fields to labels. I have also debugged dataset and it is not empty. But I can't see data on my report page.
SqlConnection conn = new SqlConnection(#"blabla");
SqlCommand select = new SqlCommand(#"select * from table",conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(select);
DataSet ds = new DataSet();
da.Fill(ds);
//ds.WriteXmlSchema(#"C:\dataset.xml");
XtraReport1 rpr = new XtraReport1();
rpr.DataSource = ds;
rpr.PrintingSystem.SetCommandVisibility(PrintingSystemCommand.ClosePreview, DevExpress.XtraPrinting.CommandVisibility.None);
rpr.CreateDocument(true);`
personally I create extensions to load and save xml Layout of reports.
I create them with an win application or whatever then save the xml layout:
public static void RestoreFromXmlXtraReportLayout(this DevExpress.XtraReports.UI.XtraReport report, string xmlXtraReportLayout)
{
if (!string.IsNullOrEmpty(xmlXtraReportLayout))
{
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".repx";
System.IO.File.WriteAllText(fileName, xmlXtraReportLayout);
report.LoadLayout(fileName);
System.IO.File.Delete(fileName);
}
}
public static string GetXmlXtraReportLayout(this DevExpress.XtraReports.UI.XtraReport report)
{
string tmpFileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".repx";
report.SaveLayout(tmpFileName);
string xmlXtraReportLayout = System.IO.File.ReadAllText(tmpFileName);
System.IO.File.Delete(tmpFileName);
return xmlXtraReportLayout;
}
using Memory Stream ( but it dosn't works fine, some data are lost, but you can try it )
public static void RestoreLayoutFromNavigationItem(this DevExpress.XtraReports.UI.XtraReport report, string xmlXtraReportLayout)
{
if (!string.IsNullOrEmpty(xmlXtraReportLayout))
{
using (Stream xmlStream = new System.IO.MemoryStream())
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlXtraReportLayout);
xDoc.Save(xmlStream);
xmlStream.Flush();
xmlStream.Position = 0;
report.LoadLayoutFromXml(xmlStream);
}
}
}
and to load the report I use a web page that contains a ASPxDocumentViewer :
<body>
<form id="formDocumentViewer" runat="server">
<div>
<dx:ASPxDocumentViewer ID="mainDocumentViewer" runat="server">
</dx:ASPxDocumentViewer>
</div>
</form>
in the page Load:
protected void Page_Load(object sender, EventArgs e)
{
report.DataSource = "your data source";
string xmlXtraReportLayout = "load it from the saved file";
report.RestoreFromXmlXtraReportLayout(xmlXtraReportLayout);
this.mainDocumentViewer.SettingsSplitter.SidePaneVisible = false;
this.mainDocumentViewer.Report = report;
}
but first you have to create your report with the report designer , load it in win application , use GetXmlXtraReportLayout to save the layout into a file.

Adding item to DataGridView by clicking button using c#

I'm writing a program for manage all customers we have in our company. I have a DataGridView where every single customer should display. And right to the DataGridView I got some textboxes, for displaying the details of every customer and for add a new customer. And I got a button "Add Customer". So if I type in some random text in textboxes and click on "Add Customer" it should add the new customer to the DataGridView. And if I restart the program, every customer should still be saved. So I save the details of every customer to a .xml file.
Can someone help me or give me a hint how I can add customers to DataGridView by clicking button? I got this code for saving to xml file:
public partial class Form1 : Form
{
const string folder = #"C:\Users\Römel\Desktop\Save";
const string basename = "save.xml";
string filename = folder + "\\" + basename;
public Form1()
{
InitializeComponent();
if (Directory.Exists(folder))
{
if (File.Exists(filename))
{
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
dataGridKunden.Columns["KundenNr"].Visible = false;
dataGridKunden.Columns["Adresse"].Visible = false;
dataGridKunden.Columns["Ort"].Visible = false;
dataGridKunden.Columns["Telefon"].Visible = false;
dataGridKunden.Columns["Mail"].Visible = false;
dataGridKunden.ScrollBars = ScrollBars.None;
}
}
private void btnAddKunde_Click(object sender, EventArgs e)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (!File.Exists(filename))
{
File.Create(filename);
}
XmlTextWriter xwriter = new XmlTextWriter(filename, Encoding.Unicode);
xwriter.WriteStartDocument();
xwriter.WriteStartElement("Kundenverwaltung");
xwriter.WriteStartElement("KundenNr");
xwriter.WriteString(txtKundenNr.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Nachname");
xwriter.WriteString(txtKundeNachname.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Vorname");
xwriter.WriteString(txtKundeVorname.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Adresse");
xwriter.WriteString(txtKundeAdresse.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Ort");
xwriter.WriteString(txtKundeOrt.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Telefon");
xwriter.WriteString(txtKundeTel.Text);
xwriter.WriteEndElement();
xwriter.WriteStartElement("Mail");
xwriter.WriteString(txtKundeMail.Text);
xwriter.WriteEndElement();
xwriter.WriteEndDocument();
xwriter.Close();
}
}
The button "Add Customer" is called "btnAddKunde".
Thanks in advance.
Cheers
Add These line of code in your button click event in last:
if (File.Exists(filename))
{
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
However, your version of XmlTextWriter will overwrite the xml file. Thus, when you click on button you will see only the latest added row. Instead you can use below code in your button click event:
private void btnAddKunde_Click(object sender, EventArgs e)
{
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
if (!File.Exists(filename))
{
using (File.Create(filename))
{}
}
XElement xmlNode = new XElement("Kundenverwaltung",
new XElement("KundenNr", txtKundenNr.Text),
new XElement("Nachname", txtKundeNachname.Text),
new XElement("Vorname", txtKundeVorname.Text),
new XElement("Adresse", txtKundeAdresse.Text),
new XElement("Ort", txtKundeOrt.Text),
new XElement("Telefon", txtKundeTel.Text),
new XElement("Mail", txtKundeMail.Text)
);
XElement xmlFile;
try
{
xmlFile = XElement.Load(filename);
xmlFile.Add(xmlNode);
}
catch (XmlException)
{
xmlFile = new XElement("Customers", xmlNode);
}
xmlFile.Save(filename);
DataSet flatDataSet = new DataSet();
flatDataSet.ReadXml(filename);
DataTable table = flatDataSet.Tables[0];
dataGridKunden.DataSource = table;
}
you need to use XMLDocument class to retrieve data from xml file
do something like this :
XDocument xmlDoc = XDocument.Load("People.xml");
xmlDoc.Element("employee").Add(new XElement("Person", new XElement("Name", txtName.Text),
new XElement("City", txtCity.Text), new XElement("Age", txtAge.Text)));
Are you lookin for an example for retrieving data from xml or just add string array retrieved from xml??
Here's how you add a string array..
string[] s = new string[4];
s[0] = "Salim";
s[1] = "9388938813"
s[2] = "s/10 santhi Nagar, Dpo road, Palakkad"
s[3] = "Kerala"
datagridView1.Rows.Add(s);
dataGridKunden.Rows.Add(new string[] {surname.text, forename.text, address.text .... });
// add as much as you want.

how to email crystal report in pdf form

I am new here and this is my first post, if there is any mistake pardon me and do let me know I'l correct it.
My question is I need to email crystal report to a particular recipient's email address which will also be included in crystal report, and that crystal report needs to be in PDF format, is this possible, if yes then can you please elaborate the procedure how to do it.
Thanks.
string pdfFile = "c:\\CrytalReport.pdf";
protected void Button1_Click(object sender, EventArgs e)
{
try
{
ExportOptions CrExportOptions;
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = pdfFile;
CrExportOptions = ReportDocument .ExportOptions;//Report document object has to be given here
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
ReportDocument .Export();
sendmail();
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
private void sendmail()
{
try
{
MailMessage Msg = new MailMessage();
Msg.To = "to Address";
Msg.From = "From Address";
Msg.Subject = "Crystal Report Attachment ";
Msg.Body = "Crystal Report Attachment ";
Msg.Attachments.Add(new MailAttachment(pdfFile));
// System.Web.Mail.SmtpMail.Send(Msg);
SmtpMail.SmtpServer = "you mail domain";
//SmtpMail.SmtpServer.Insert(0,"127.0.0.1");
SmtpMail.Send(Msg);
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}
Don't forget add these DLL's
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;
/// <summary>
/// Summary description for CrystalReport
/// </summary>
'public class CrystalReport
{
private void SetDBLogOnInfo(ConnectionInfo connectionInfo, ReportDocument objectReportDocument, TableLogOnInfo tableLogonInfo)
{
Tables Tbl = objectReportDocument.Database.Tables;
foreach (CrystalDecisions.CrystalReports.Engine.Table TmpTbl in Tbl)
{
tableLogonInfo = TmpTbl.LogOnInfo;
tableLogonInfo.ConnectionInfo = connectionInfo;
TmpTbl.ApplyLogOnInfo(tableLogonInfo);
}
}
public ReportDocument CrystalLogon(String pReportPath, ConnectionInfo objConnInfo, ref TableLogOnInfo tableLogonInfo)
{
ReportDocument objReportDoc = new ReportDocument();
objReportDoc.Load(pReportPath);
SetDBLogOnInfo(objConnInfo, objReportDoc, tableLogonInfo);
return objReportDoc;
}
public string[] GetCampaignConn()
{
//string server, database, userid, password;
string strConn = System.Configuration.ConfigurationSettings.AppSettings["Connection String"];
string[] strArray = strConn.Split(';');
string[] strOutput = new string[4];
for (int i = 0; i < strArray.Length; i++)
{
string[] strObject = strArray[i].Split('=');
if (strObject[0] == "Data Source")
{
strOutput[0] = strObject[1];
}
else if (strObject[0] == "Initial Catalog")
{
strOutput[1] = strObject[1];
}
else if (strObject[0] == "User ID")
{
strOutput[2] = strObject[1];
}
else if (strObject[0] == "Password")
{
strOutput[3] = strObject[1];
}
}
return strOutput;
}
}`
use above method you will problem will resolved
private void SetReportDataSource(string sCarrierID)
{
try
{
CrystalReport objCrystalReport = new CrystalReport();
//ReportDocument objReportDoc = new ReportDocument();
ConnectionInfo objConnInfo = new ConnectionInfo();
//string strConn = System.Configuration.ConfigurationSettings.AppSettings[Campaign];
string[] strArray = objCrystalReport.GetCampaignConn();
CrystalDecisions.Shared.TableLogOnInfo logOnInfo = new CrystalDecisions.Shared.TableLogOnInfo();
objConnInfo.DatabaseName = strArray[1].ToString();
objConnInfo.UserID = strArray[2].ToString();
objConnInfo.Password = strArray[3].ToString();
objConnInfo.ServerName = strArray[0].ToString();
String ReportPath = (Server.MapPath("Report") + #"\rptInvoice.rpt");
//String ReportPath = Server.MapPath("~//Report//VendorRegistration.rpt");
//objReportDoc = objCrystalReport.CrystalLogon(ReportPath, objConnInfo, ref logOnInfo);
//// for displaying Crystal report
//crVendorRegistration.ReportSource = objReportDoc;
//crVendorRegistration.ParameterFieldInfo[0].CurrentValues.Clear();
ParameterDiscreteValue pdvalue = new ParameterDiscreteValue();
pdvalue.Value = Convert.ToInt32(sCarrierID);
//crVendorRegistration.ParameterFieldInfo[0].CurrentValues.Add(pdvalue);
//crVendorRegistration.DataBind();
//// for Exporitng in PDF
ReportDocument repDoc = objCrystalReport.CrystalLogon(ReportPath, objConnInfo, ref logOnInfo);
repDoc.ParameterFields[0].CurrentValues.Add(pdvalue);
// Stop buffering the response
HttpContext.Current.Response.Buffer = false;
// Clear the response content and headers
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
// Export the Report to Response stream in PDF format and file name Customers
//repDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, HttpContext.Current.Response, true, "Truck Invoice " + sCarrierID + "");
//repDoc.GenerateReport
String ReportGenerated = (Server.MapPath("GenerateReport") + #"\rptInvoice" + sCarrierID + ".pdf");
// There are other format options available such as Word, Excel, CVS, and HTML in the ExportFormatType Enum given by crystal reports
ExportOptions CrExportOptions = new ExportOptions();
DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = ReportGenerated;
CrExportOptions = repDoc.ExportOptions;
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
repDoc.Export(CrExportOptions);
//pdvalue = new ParameterDiscreteValue();
//pdvalue.Value = QC_By;
//crSalesRpt.ParameterFieldInfo[1].CurrentValues.Add(pdvalue);
//objReportDoc.VerifyDatabase();
//objReportDoc.Refresh();
}
catch (Exception ex)
{
//bool rethrow = ExceptionPolicy.HandleException(ex, "");
//if (rethrow)
// throw;
//Redirecting to error message page
//Server.Transfer(ConstantClass.StrErrorPageURL);
}
}
by above you create pdf using crystal report by using mail concept u will sending mail thats it

Categories