Why getting this error :Specified cast is not valid - c#

I am using this code to open crystal report in VS2010 ,axCRViewer1 is crystal report viewer control name , but getting error at this line
axCRViewer1.ReportSource = rptDoc;
How do I fix it ?
private void ViewR_Load(object sender, EventArgs e)
{
ReportDocument rptDoc = new ReportDocument();
DataSetPatient ds = new DataSetPatient(); // .xsd file name
DataTable dt1 = new DataTable();
DataTable dt = DBHandling.GetPatient();//getting data using GetPatient()
// Just set the name of data table
dt.TableName = "Crystal Report P";
ds.Tables[0].Merge(dt);
// Your .rpt file path will be below
rptDoc.Load("C:\\Users\\Monika\\Documents\\Visual Studio 2010\\Projects\\SonoRepo\\SonoRepo\\Reports\\CrystalReportP.rpt");
//set dataset to the report viewer.
rptDoc.SetDataSource(ds);
axCRViewer1.ReportSource = rptDoc;//getting error at this line
// code to get data from the DB
}
Getpatient() Code
public static DataTable GetPatient()
{
DataTable patientTable = new DataTable();
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sonorepo.mdb"))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(#"SELECT PatientID,PFirstName FROM Patient_Registration", con))
da.Fill(patientTable);
}
return patientTable;
}

This message is coming from the data. Check if the structure of DataTable dt is the same as the structure of the first table in DataSetPatient.
You can also try to replace the code for DataSetPatient.
DataSetPatient ds = new DataSetPatient(); // .xsd file name
....
ds.Tables[0].Merge(dt);
with
DataSet ds = new Dataset()
ds.Tables.Add

Here is what worked for me:
If you are installing on a 64-bit machine, make sure the application properties under the Build tab have "Any CPU" as the platform target, and unselect the check box for "Prefer 32-bit" if you have the option. Crystal is very touchy about 32/64 bit assemblies, and makes some pretty counterintuitive assumptions which are very difficult to troubleshoot.

Related

How can I redirect to Report Viewer?

I am facing a problem while working with Reports in WPF... I have created an event
private void Window_Loaded(object sender, RoutedEventArgs e) {
try {
admissionReportViewer.Owner = Window.GetWindow(this);
if (_admissionNumber != 0) {
rd.Load(#"C:\\Users\Sohaib Khalid\source\repos\SMS Degree College\Reports\AdmissionForm - Copy.rpt");
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Other"].ConnectionString;
conn.Open();
SqlDataAdapter sda = new SqlDataAdapter("SearchStudentInfoAllById", conn);
sda.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
sda.SelectCommand.Parameters.AddWithValue("#AdmissionNumber", _admissionNumber);
sda.SelectCommand.Parameters.AddWithValue("#Active", _active);
DataSet ds = new DataSet();
sda.Fill(ds, "StudentTable");
rd.SetDataSource(ds);
admissionReportViewer.ViewerCore.ReportSource = rd;
}
}
catch(Exception err) {
this.ShowMessageAsync("No data", err.ToString());
Debug.WriteLine(err.ToString());
}
after this report also load but it again, ask for parameters:
and also credentials of server login
Can Anybody tell me why it is again asking for parameters?
Thanks
I never used ReportViewer in WPF app, but used it a couple of time on ASP.NET
If WPF works in the same way, you're code is wrong:
The report is using the data source you set up for design it and not the one you're passing to it
You're storing the parameter value in the data adapter (query) and not in the report parameters
This is why your report ask for both.
I'll share a bit of code for ASP, try to check if it can be the same for WPF or if you have to change it:
// Local mode says to use the datasource we are giving to the report
// instead of the one we used to design it
reportViewer.ProcessingMode = ProcessingMode.Local;
// Set the path of the report file
LocalReport localReport = reportViewer.LocalReport;
localReport.ReportPath = "PATH_OF_YOUR_REPORT";
// Extract data from the DB (remember to insert the parameters in the query)
var dataset = GetDataSet();
// Assign the dataset to the report source (we need a ReportDataSource)
var source = new ReportDataSource();
source.Name = "SOURCE_NAME_USED_IN_THE_REPORT";
source.Value = dataset.Tables["YOUR_TABLE"];
// Add the source to the report
localReport.DataSources.Add(source);
// Create your report parameter (ex: fromDate)
var paramFromDate = new ReportParameter();
paramDataDa.Name = "fromDate";
paramDataDa.Values.Add(paramFromDate.ToShortDateString());
// Set the report parameters for the report
localReport.SetParameters(new ReportParameter[] { fromDate });
I hope this can help you but remember, it is for ASP and not for WPF.
So try to adapt it to WPF and see if they work in the same way

Report fails to print and export to PDF

I'm working with an asp.net web form Crystal report. The report generates when I pass the parameter but it fails to print and export to PDF. Nothing happens when I click the export button, and there is no error message.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString);
ReportDocument test = new ReportDocument();
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT_DATA", cn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable ds = new DataTable();
cmd.Parameters.Add(new SqlParameter("#INPUT", TextBox1.Text));
da.Fill(ds);
test.Load(Server.MapPath("EOR.rpt"));
test.SetDataSource(ds);
test.SetParameterValue("input", TextBox1.Text);
CrystalReportViewer1.ReportSource = test;
CrystalReportViewer1.DataBind();
cn.Close();
}
I copied the file to my website project:
Copy
C:\inetpub\wwwroot\aspnet_client\system_web\4_0_30319 folder and
paste to my project folder
Try checking the browser javascript console to see if there's a problem linked to CrystalReportViewer missing a js reference (*bobj is undefined*).
In that case, try to add to your printing page the script reference to the crv.js file (In the folder you paste in your project. Mine was located at 4_0_30319/crystalreportviewers13/js/crviewer/crv.js)

two reports in one reportViewer

I have one reportviewer called reportviewer1
and two reports (report1.rdlc,report2.rdlc)
i want to display them into the reportviwer1 by choosing one of them in combo box by using the code
i tried the following code
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1"));
reportViewer1.LocalReport.ReportEmbeddedResource = "university_project.Report1.rdlc";
reportViewer1.LocalReport.Refresh();
but it didn't work
what is the correct format of the code?is there a missing parameters in the ReportDataSource?
You need to specify where the records are coming from (fill a dataSet) and set the LocalPath of the reportViewer:
var dataSet = new DataSet();
using (var connection = new SqlConnection("ConnectionString"))
{
var sqlAdapter = new SqlDataAdapter("SELECT * FROM TABLE1",connection); // Get the records
sqlAdapter.Fill(dataSet, "Table1");
}
ReportViewer1.Reset();
ReportViewer1.LocalReport.Path = "university_project.Report1.rdlc"; // Path to your report file
var dataSource = new ReportDataSource("ReportDataSet_Name", dataSet.Tables[0]); // Specify report's dataset name and the records it use
ReportViewer1.LocalReport.DataSources.Clear(); // Clean the sources so you can use different datasources each time
ReportViewer1.LocalReport.DataSources.Add(datasource);
ReportViewer1.LocalReport.Refresh();
You need to pass DataTable too:
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", myDataTableWithData));

report viewer in windows form not updating even after refresh report

i am try to generate report via report viewer using click event on button. its working fine. but when i update my data in database report viewer show only old report . i have tried using refresh report too.its not working. i am using table adapter in dataset to populate my data.
this.reportViewer1.Reset();
Microsoft.Reporting.WinForms.ReportDataSource reportDataSource2 = new Microsoft.Reporting.WinForms.ReportDataSource();
reportDataSource2.Name = "LedgerBy_partyID";
reportDataSource2.Value = this.Ledger_by_Party_IDBindingSource;
// this.ReportDataset.Ledger_by_Party_ID.Reset();
this.Ledger_by_Party_IDTableAdapter.Fill(this.ReportDataset.Ledger_by_Party_ID, selected_PartyID);
this.reportViewer1.LocalReport.ReportEmbeddedResource = "proj.userReport.Ledger_ByPartyID.rdlc";
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(reportDataSource2);
this.reportViewer1.LocalReport.Refresh();
this.reportViewer1.RefreshReport();
I just solved the same problem. I was searching for a few days in internet but I couldn't find a good answer for it. So I hope my post will help somebody to overcome the same problem.
All you need to do - just define manually the connection, refill the dataset and bind the source to reportviewer. Here is my project example:
using Microsoft.Reporting.WinForms;
private void ReportForm_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\GD Robotics\VisualProjects\GDPolin\GDPolin\PolinaDB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlDataAdapter reportDBTableAdapter = new SqlDataAdapter("SELECT * FROM [ReportDB]", conn);
DataTable polinaDBDataSet = new DataTable();
reportDBTableAdapter.Fill(polinaDBDataSet);
conn.Close();
this.reportViewer1.Reset();
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.ReportPath = #"D:\GD Robotics\VisualProjects\GDPolin\GDPolin\Report1.rdlc";
ReportDataSource rds = new ReportDataSource("DataSet1", polinaDBDataSet);//"DataSet1" is the name of your dataset. Go to .rdlc form>VIEW>Report Data>"Right click on dataset">Dataset Properties
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.RefreshReport();
}

adding crystal report via code

i successfully designed and filled my Crystal report via code not via wizard.
i added Crystal report via addNEWITEM
i added dataset in aap_code via addNEWITEM
i added datatable into dataset via addNEWITEM
Via code i made report and filled dataset and table with data
Run and display. Successfully done.
but my question is that how to do it fully via code like for steps 1,2,3 ? I don't want to add it via AddNewItem etc, isn't there any way to add these via code ? i did, i created some datasets and table via code like we do for Gridview etc but that doesn't appear in DATA connections of crystal report etc.
String conStr =WebConfigurationManager.ConnectionStrings["LoginDatabaseConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Dataset_load();
}
}
protected void Dataset_load()
{
SqlConnection sqlcon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom);
// DataSet ds = new DataSet("CRDataSet");
try
{
sqlcon.Open();
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataSet1 ds = new DataSet1();
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("CrystalReport.rpt"));
rd.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rd;
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
sqlcon.Close();
}
I'm not sure why you would make it harder on yourself by trying to create all the code from scratch rather than using the functionality of VS. If you really want to do it though, I would create everything using the built-in functionality. Then I would look at all the code that gets added and see what does what.
There are some tutorials out there that tell you how to do it using the features. Create one and then read through the code.
That's how I would do it.
Hope that helps,
Chris

Categories