How to View Crystal report in Visual Studio 2013? - c#

I'm working on ASP.Net with C#, and installed CrystalReport 13 for Visual Studio 2013. I wrote code to fill a Datasource and pass it into my `CrystalReport file, but my website doesn't show anything. How can I execute my report?
Here is my PageLoad:
SqlConnection cnn = new SqlConnection(connectionstring);
cnn.Open();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
command.Connection = cnn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "STP_T00050030";
command.Parameters.Add("#F_CNTRowID", SqlDbType.Int).Value = Convert.ToInt32("20");
command.Parameters.Add("#F_CNTid", SqlDbType.Int).Value = Convert.ToInt32("45");
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("~/Report1.rpt"));
crystalReport.SetDataSource(ds);
CrystalReportViewer1.ReportSource = crystalReport;

In your solution, right mouse click on each report (.rpt file) and go properties --> Build Action=Content, Copy To Output Directory=Copy Always
Here's a complete block of code for setting data source. Notice how data source must also be set for each subreport.
public static CrystalReportSource Crystal_SetDataSource(string reportName, object par1, object par2, object par3)
{
CrystalReportSource CrystalReportSource2 = new CrystalReportSource();
CrystalReportSource2.CacheDuration = 10;
CrystalReportSource2.Report.FileName = #"~\App_Pages\Secure\Reports\" + reportName;
CrystalDecisions.CrystalReports.Engine.Database crDatabase = CrystalReportSource2.ReportDocument.Database;
ConnectionInfo crConnectionInfo = new ConnectionInfo();
crConnectionInfo.ServerName = server;
crConnectionInfo.DatabaseName = db;
crConnectionInfo.UserID = crystalUser;
crConnectionInfo.Password = pwd;
crConnectionInfo.IntegratedSecurity = false;
// First we assign the connection to all tables in the main report
TableLogOnInfo crTableLogOnInfo = new TableLogOnInfo();
foreach (CrystalDecisions.CrystalReports.Engine.Table crTable in crDatabase.Tables)
{
crTableLogOnInfo = crTable.LogOnInfo;
crTableLogOnInfo.ConnectionInfo = crConnectionInfo;
crTable.ApplyLogOnInfo(crTableLogOnInfo);
}
//SET DATASOURCE FOR EACH SUBREPORT IN REPORT
foreach (CrystalDecisions.CrystalReports.Engine.Section section in CrystalReportSource2.ReportDocument.ReportDefinition.Sections)
{
// In each section we need to loop through all the reporting objects
foreach (CrystalDecisions.CrystalReports.Engine.ReportObject reportObject in section.ReportObjects)
{
if (reportObject.Kind == ReportObjectKind.SubreportObject)
{
SubreportObject subReport = (SubreportObject)reportObject;
ReportDocument subDocument = subReport.OpenSubreport(subReport.SubreportName);
foreach (CrystalDecisions.CrystalReports.Engine.Table table in subDocument.Database.Tables)
{
// Cache the logon info block
TableLogOnInfo logOnInfo = table.LogOnInfo;
// Set the connection
logOnInfo.ConnectionInfo = crConnectionInfo;
// Apply the connection to the table!
table.ApplyLogOnInfo(logOnInfo);
}
}
}
}
if (CrystalReportSource2.ReportDocument.DataSourceConnections.Count > 0)
CrystalReportSource2.ReportDocument.DataSourceConnections[0].SetConnection(server, db, crystalUser, pwd);
CrystalReportSource2.ReportDocument.SetDatabaseLogon(crystalUser, pwd, server, db);
if (par1 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(0, par1);
if (par2 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(1, par2);
if (par3 != null)
CrystalReportSource2.ReportDocument.SetParameterValue(2, par3);
return CrystalReportSource2;
}

Related

sap crystalreport c# add-on logonfailed

i'm too getting too stuck trying to solve this issue i try to print directly value from my sap add-on using c# in visualstudio 2010 it's return for me this error:
'logonfailed' here is my code :
try
{
DataTable matable = new DataTable();
DataSet madataset = new DataSet();
SqlConnection maconnexion = new SqlConnection();
maconnexion.ConnectionString = Menu.connectionString_formatsql;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select oitm.ItemCode ,OITM .ItemName ,OITM .CodeBars,ITM1.Price,#codebars " +
" from OITM,ITM1 where OITM .ItemCode=ITM1 .ItemCode" +
" and OITM.ItemCode =#itemCode" +
" and ITM1 .PriceList = #pricelist ";
cmd.Parameters.Clear();
//cmd.Parameters.Add("#codebars", SqlDbType.VarChar );
//cmd.Parameters["#codebars"].Value = get_codebarre_dessin();
//cmd.Parameters.Add("#itemCode", SqlDbType.VarChar);
//cmd.Parameters["#itemCode"].Value = this.EditText1.Value;
//cmd.Parameters.Add("#pricelist", SqlDbType.SmallInt);
//cmd.Parameters["#pricelist"].Value = Convert.ToInt32(this.ComboBox0.Value);
cmd.Parameters.Add("#codebars", SqlDbType.VarChar);
cmd.Parameters["#codebars"].Value = get_codebarre_dessin();
cmd.Parameters.Add("#itemCode", SqlDbType.VarChar);
cmd.Parameters["#itemCode"].Value = this.EditText1.Value;
cmd.Parameters.Add("#pricelist", SqlDbType.Int);
cmd.Parameters["#pricelist"].Value = Convert.ToInt32(this.ComboBox0.Value);
cmd.Connection = maconnexion;
if (maconnexion.State == ConnectionState.Closed)
{
maconnexion.Open();
}
SqlDataAdapter madataadapter = new SqlDataAdapter(cmd);
// SqlCommandBuilder madatabuilder = new SqlCommandBuilder(madataadapter );
matable.Load(cmd.ExecuteReader());
madataset.Tables.Add(matable);
ReportDocument report = new ReportDocument();
report.Load("BARCODE.rpt");
report.Refresh();
report.DataSourceConnections.Clear();
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
MessageBox.Show( tableLogOnInfo.ConnectionInfo.ServerName );
MessageBox.Show( tableLogOnInfo.ConnectionInfo.DatabaseName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.UserID);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.Password.ToString());
MessageBox.Show(tableLogOnInfo.ConnectionInfo.IntegratedSecurity.ToString() );
//table.ApplyLogOnInfo(tableLogOnInfo);
//table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
tableLogOnInfo.ConnectionInfo.AllowCustomConnection = true;
tableLogOnInfo.ConnectionInfo.ServerName = Menu.company.Server;
tableLogOnInfo.ConnectionInfo.DatabaseName = Menu.company.CompanyDB;
//tableLogOnInfo.ConnectionInfo.UserID = Menu.company.UserName;
//tableLogOnInfo.ConnectionInfo.Password = Menu.company.Password;
tableLogOnInfo.ConnectionInfo.UserID = Menu .company.DbUserName;
tableLogOnInfo.ConnectionInfo.Password = Menu.company.DbPassword;
tableLogOnInfo.ConnectionInfo.IntegratedSecurity = false ;
table.ApplyLogOnInfo(tableLogOnInfo);
table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
foreach (CrystalDecisions.CrystalReports.Engine.Table table in report.Database.Tables)
{
TableLogOnInfo tableLogOnInfo = table.LogOnInfo;
MessageBox.Show(tableLogOnInfo.ConnectionInfo.ServerName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.DatabaseName);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.UserID);
MessageBox.Show(tableLogOnInfo.ConnectionInfo.Password.ToString());
MessageBox.Show(tableLogOnInfo.ConnectionInfo.IntegratedSecurity.ToString());
//table.ApplyLogOnInfo(tableLogOnInfo);
//table.Location = Menu.company.CompanyDB + ".dbo." + table.Name.ToString();
}
report.SetDataSource(matable);
report.SetDatabaseLogon(Menu.company.DbUserName, Menu.company.DbPassword);
PrinterSettings settings = new PrinterSettings();
PrintDialog pdialog = new PrintDialog();
pdialog.PrinterSettings = settings;
pdialog.AllowPrintToFile = true;
pdialog.AllowSomePages = true;
pdialog.UseEXDialog = true;
// ParameterFields parameterFields = report.ParameterFields;
//report.SetParameterValue(0, this.ComboBox0.Value);
//report.SetParameterValue(1, EditText1.Value.ToString());
//report.SetParameterValue(2, get_codebarre_dessin());
report.SetParameterValue(2, this.ComboBox0.Value);
report.SetParameterValue(1, EditText1.Value.ToString());
report.SetParameterValue(0, get_codebarre_dessin());
report.PrintOptions.PrinterName = ComboBox1.Value;
//report.PrintToPrinter(settings, new PageSettings() { }, false);
report.PrintToPrinter(1, true, 1, System.Convert.ToInt32(EditText0.Value));
maconnexion.Close();
}
catch (LogOnException engEx)
{
MessageBox.Show("Incorrect Logon Parameters. Check your user name and password." + engEx.ErrorID);
}
catch (DataSourceException engEx)
{
MessageBox.Show("An error has occurred while connecting to the database.");
}
catch (EngineException engEx)
{
MessageBox.Show(engEx.Message);
}

How to print multiple instance of crystal report using single Crystal Report Viewer in c#

I am trying to print multiple crystal report using single Crystal Report Viewer.
I have 'n' number of items in a database and I need to print 'n' crystal reports. As it is dynamic in nature so I cannot fix number of Report Viewer, so I thought to use single Report Viewer and load crystal report using 'For loop'.
I created a new datatable in dataset and I was trying to put value from another datatable it didnt worked out so created parameter fields and is putting values in through
For Loop
Here my code(I have 3 parameter fields for ease of viewing showing only one):
private void CRVtakeout_Load(object sender, EventArgs e)
{
try
{
string sqlqry = "Select KOTNo,Time,TableNo,WaiterName,ItemCode,ItemName,Quantity,Amount,Foodtype From tblOrder Where KOTNo=#kotno";
SqlCommand cmd = new SqlCommand(sqlqry, connectionclass.con);
cmd.Parameters.AddWithValue("#kotno", NewOrderBL.KOTNo);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet1 ds = new DataSet1();
adapter.Fill(ds, "Takeout");
//adapter.Fill(ds, "Takeout");
string tableno = ds.Tables["Takeout"].Rows[i][2].ToString();
tableno = tableno.Substring(6, 1);
if (ds.Tables["Takeout"].Rows.Count == 0)
{
MessageBox.Show("No Data Found", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (tableno == "T")
{
for (int i = 0; i < ds.Tables["Takeout"].Rows.Count; i++)
{
crystalReportViewer1.RefreshReport();
ParameterFields paramFields = new ParameterFields();
ParameterField paramField = new ParameterField();
ParameterDiscreteValue paramDiscreteValue = new ParameterDiscreteValue();
paramField.Name = "Billno";
paramDiscreteValue.Value = ds.Tables["Takeout"].Rows[0][0].ToString();
paramField.CurrentValues.Add(paramDiscreteValue);
paramFields.Add(paramField);
printtakeout printtakeout = new printtakeout();
printtakeout.SetDataSource(ds);
crystalReportViewer1.ReportSource = printtakeout;
System.Drawing.Printing.PrintDocument printdocument = new System.Drawing.Printing.PrintDocument();
printtakeout.PrintOptions.PrinterName = printdocument.PrinterSettings.PrinterName;
printtakeout.PrintOptions.PrinterName = "EPSON TM-U220 Receipt";
printtakeout.PrintToPrinter(1, false, 0, 0);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally { connectionclass.disconnect(); }**strong text**
}
Each time I do it gives error :
activex control 8856f961-340a-11d0-a96b-00c04fd705a2 cannot be instantiated because the current thread is not a single-thread apartment
If I dont use parameter field theirs no error.
If any clarification needed please do tell.
Thanks .
There is an example to do queries
using (SqlConnection connection = new SqlConnection("connectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT * FROM Customers";
command.CommandType = CommandType.Text;
using (SqlDataReader objDataReader = command.ExecuteReader())
{
if (objDataReader != null)
{
while (objDataReader.Read())
{
// To get results...
// objDataReader["NameResultParam"];
}
}
}
}

Convert Crystalreport's Provider from 'SQLNCLI' to 'SQLOLEDB' by code (c#)

Is it possible to convert crystalreport's Provider from 'SQLNCLI' to 'SQLOLEDB' by code "c#"
I have tried with following code but did not work.
TableLogOnInfo logoninfo;
foreach (CrystalDecisions.CrystalReports.Engine.Table tbcurrent in rptH.Database.Tables)
{
logoninfo = new TableLogOnInfo();
logoninfo.ConnectionInfo.DatabaseName = connectionInfo.DatabaseName;
logoninfo.ConnectionInfo.ServerName = connectionInfo.ServerName;
logoninfo.ConnectionInfo.UserID = connectionInfo.UserID;
logoninfo.ConnectionInfo.Password = connectionInfo.Password;
tbcurrent.ApplyLogOnInfo(logoninfo);
}
rptH.SetDatabaseLogon(connectionInfo.UserID, connectionInfo.Password, connectionInfo.ServerName, connectionInfo.DatabaseName, true);
for (int i = 0; i < rptH.Subreports.Count; i++)
{
foreach (CrystalDecisions.CrystalReports.Engine.Table tbcurrent in rptH.Subreports[i].Database.Tables)
{
logoninfo = new TableLogOnInfo();
logoninfo.ConnectionInfo.DatabaseName = connectionInfo.DatabaseName;
logoninfo.ConnectionInfo.ServerName = connectionInfo.ServerName;
logoninfo.ConnectionInfo.UserID = connectionInfo.UserID;
logoninfo.ConnectionInfo.Password = connectionInfo.Password;
tbcurrent.ApplyLogOnInfo(logoninfo);
}
rptH.Subreports[i].SetDatabaseLogon(connectionInfo.UserID, connectionInfo.Password, connectionInfo.ServerName, connectionInfo.DatabaseName, true);
}
I am not sure if this can be done as the connection type seems to be stored in the .rpt file.
But you can try use native .Net API to retrieve database selection into a System.Data.DataSet / System.Data.DataTable instance and call Table.SetDataSource() to set as the table data source, so you do not need to care about TableLogOnInfo object, but please ensure the scheme matches that of the report.
Below sample codes are from Crystal Reports .NET API Guide:
private void SetDataSource
(string conn, string query, DataSet dataSet)
{
OleDbConnection oleConn = new OleDbConnection(conn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = new OleDbCommand(query, oleConn);
oleAdapter.Fill(dataSet, "Customer");
reportDocument.Database.Tables["Customer"].SetDataSource (dataSet);
}
Besides, ReportDocument also has SetDataSource() method, so you can set the data source for the whole report.

Crystal REport throws error on formula field while exporting to pdf using c#

I have crystal report that is build on a view that uses 2 tables and around 47 columns. this was created in cr 2008. now I have to import this report into c# asp.net project and use dataset I have created to work as a data source for this same report. it giving error stating that a formula fields that are created using a view are throwing an error which is something like this
This field name is not known.
Details: errorKindError in File statement {C4B51C11-81BC-4D27-9886-23BE50D5A9D0}.rpt:
Error in formula Location:
'if {statements_view.DOC_TYPE} = 'RU' then
{statements_view.BUNUMBER_RU}
else {statements_view.BUNUMBER}
am I missing something here ?
here is my code so far
string connetionString = null;
OracleConnection connection;
OracleDataAdapter OracleAdapter;
DataSet ds = new DataSet();
string firstSql = null;
string secondSql = null;
connetionString = "DATA SOURCE= blah blah ";
firstSql = "select * from STATEMENT_DOMESTIC";
secondSql = "Select * from STATEMENT_DOM_DETAILS";
connection = new OracleConnection(connetionString);
connection.Open();
OracleAdapter = new OracleDataAdapter(firstSql, connection);
OracleAdapter.Fill(ds, "Tables[0]");
OracleAdapter.SelectCommand.CommandText = secondSql;
OracleAdapter.Fill(ds, "tables[1]");
OracleAdapter.Dispose();
connection.Close();
// GridView1.DataSource = ds;
// GridView1.DataBind();
ReportDocument reportDoc = new ReportDocument();
reportDoc.Load(#"c:\statement.rpt");
reportDoc.SetDataSource(ds.Tables);
ExportOptions CrExportOptions;
DiskFileDestinationOptions CrDiskFileDestinationOptions =new DiskFileDestinationOptions();
PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
CrDiskFileDestinationOptions.DiskFileName = #"d:\Converte5_1_13.pdf";
CrExportOptions = reportDoc.ExportOptions;
{
CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
CrExportOptions.FormatOptions = CrFormatTypeOptions;
}
reportDoc.Export();
}
is there a problem with my dataset or am I missing something here..
any guidance on this issue is

Loss of Data after printing my crystal report via PrintToPrinter

after printing the document using PrintToPrinter all data is lost, dont know why ????
this code had one more problem, I hve rectified the problem by adding :
rpt.SetDatabaseLogon("u","p");
and now I have empty document printed.
this is my code:
protected void btnPrintToPrinter_Click(object sender, EventArgs e)
{
int empno = Convert.ToInt32(Session["AnyVal"]);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string strQuery = "SELECT [View_EmplDetail].[Uni-Code], [View_EmplDetail].[FacultyCode], [View_EmplDetail].[EmpIDstr], [View_EmplDetail].[EngGivenName], [View_EmplDetail].[position_eng], [View_EmplDetail].[Emp_no], [View_EmplDetail].[GivenName], [View_EmplDetail].[position_name], [View_EmplDetail].[DariName], [Tbl_Dept].[EName], [View_EmplDetail].[photo] FROM [MoHEDatabase].[dbo].[View_EmplDetail] [View_EmplDetail] INNER JOIN [MoHEDatabase].[dbo].[Tbl_Dept] [Tbl_Dept] ON [View_EmplDetail].[DepCode]=[Tbl_Dept].[DepCode] WHERE [Emp_no] = #empno";
SqlCommand command = new SqlCommand(strQuery, connection);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#empno", empno);
command.Connection = connection;
command.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
ReportDocument rpt = new ReportDocument();
string _reportPath = Server.MapPath("..\\Student\\cardFinal.rpt");
//rpt.Load(AppDomain.CurrentDomain.BaseDirectory + "\\" + #"\\Student\\CardFinal.rpt");
rpt.Load(_reportPath);
rpt.SetDataSource(dt);
emp_card_report_viewer.ReportSource = rpt;
string sq = "";
//{View_OrgStr1.Uni-Code}=0 and {View_OrgStr1.FacultyCode}=119
//sq = "{View_StudentAddNew.Student_ID}=" + Session["AnyVal"];
if (Session["AnyVal"].ToString() != "")
{
sq = "{View_EmplDetail.Emp_no}=" + int.Parse(Session["AnyVal"].ToString());
}
//emp_card_report.Report.FileName = "../Student/CardFinal.rpt";
emp_card_report_viewer.SelectionFormula = sq;
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "172.16.0.15";
//connInfo.DatabaseName = "MoHEMISDatabase";
//connInfo.UserID = "hemis_admin";
//connInfo.Password = "hemis#sabir";
//TableLogOnInfos crtt = new TableLogOnInfos();
//TableLogOnInfo crtto = new TableLogOnInfo();
//Tables crtables;
//crtables = rpt.Database.Tables;
//foreach (CrystalDecisions.CrystalReports.Engine.Table crtable in crtables)
//{
// crtto = crtable.LogOnInfo;
// crtto.ConnectionInfo = connInfo;
// //crtable.ApplyLogInInfo(crtto);
//}
ConnectionInfo connInfo1 = new ConnectionInfo();
// connInfo1.ServerName = "server";
setDBLOGONforReport(connInfo1);
//emp_card_report_viewer.RefreshReport();
//ConnectionInfo connInfo = new ConnectionInfo();
//connInfo.ServerName = "server";
//connInfo.DatabaseName = "MoHEDatabase";
//connInfo.UserID = "hemis_admin";
//connInfo.Password = "hemis#sabir";
//setDBLOGONforReport(connInfo);
CrystalDecisions.Shared.PageMargins pageMargins = new
CrystalDecisions.Shared.PageMargins(0, 0, 0, 0);
rpt.PrintOptions.ApplyPageMargins(pageMargins);
rpt.PrintOptions.PrinterName = printerList.SelectedItem.Value;
emp_card_report_viewer.RefreshReport();
rpt.PrintToPrinter(1, false, 1, 1);
rpt.Close();
rpt = null;
}
THE ANSWER:
I was using Select Expert Record in the crystal report , I removed all formula in Select Expert and it worked .... :)

Categories

Resources