adding crystal report via code - c#

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

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

Crystal report shows only one page C#

I'm using crystal reports in a C# Windows Form application to generate a report from a dataset, everything works fine but it only generates one page of the report for example if I have 20 rows in my dataset and the report page fits only 10 I will get the first ten and no other pages. How can I make a multiple page report what am I doing wrong ?
Here is code that I'm using:
SqlConnection conn = new SqlConnection();
conn = dbclass.getconnection();
conn.Open();
// Create the command
SqlCommand command = new SqlCommand(scmd, conn);
SqlDataAdapter adapter = new SqlDataAdapter(command);
allcrsds ds = new allcrsds();
adapter.Fill(ds, "allcars");
adapter.Dispose();
dataGridView1.DataSource = ds.Tables["allcars"].DefaultView;
allrp.SetDataSource(ds);
ds.Dispose();
conn.Close();
thats how i made the report
thats the report i get

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();
}

Why getting this error :Specified cast is not valid

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.

Passing a Parameter - ReportViewer local mode

Am tyring to pass a parameter in a local report using a ReportViewer control in VS2010. The user clicks on a merchant, and there is a button press (not shown) which then renders the report.
I've tried using this video : How-to Pass Parameter to Report Viewer - YouTube
Problem: Code doesn't work - near xxxx at the bottom I can't figure out what should be in there
Problem: I would love to get rid of this code and use linqtosql or something simpler.
protected void Page_Load(object sender, EventArgs e)
{
DataSet1TableAdapters.MerchantNamesTableAdapter merchantNamesTableAdapter = new DataSet1TableAdapters.MerchantNamesTableAdapter();
ddlMerchants.DataSource = merchantNamesTableAdapter.GetDataAllMerchants();
ddlMerchants.DataTextField = "Name";
ddlMerchants.DataValueField = "MerchantUID";
ddlMerchants.DataBind();
ReportViewer1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
ReportViewer1.Visible = true;
var newDataSet = new DataSet();
SqlConnection sqlConnection = new SqlConnection("Data Source=.;Initial Catalog=myDataBase;Integrated Security=True");
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "select * from merchant where merchantUID = #MerchantUID";
sqlCommand.Parameters.AddWithValue("#MerchantUID", ddlMerchants.SelectedValue);
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(newDataSet);
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables(0));
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
ReportViewer1.LocalReport.Refresh();
}
In scenario like this I usually follow this path:
I create a dataset for the report: select the report and the menu command View - Report Data; in the Report Data windows select New ... - Dataset. I enter a name for the dataset (suppose Redemptions) and I select New ... next by DataSource, then I select Object and I navigate to my domain (or dto) class. That done I see the fields of my class and I can use it in the report;
If needed I create parameters in the Report Data Windows (right click on the Parameters Node) and define the name and type of the parameter;
I write this code to pass the data and parameters (if needed) to the report:
viewer.Reset();
ReportDataSource dataSource = new ReportDataSource();
// I use a service/repository; you could also use Linq2Sql or EntityFramework
IList<Redemption> redemptions = _service.GetRedemptions(merchantId);
BindingSource bindingSource = new BindingSource(redemptions, string.Empty);
dataSource.Name = "Redemptions";
dataSource.Value = bindingSource;
viewer.LocalReport.DataSources.Add(getDataSource(sourceInfo));
String reportName = "AD.Conso.MyReport.rdlc";
viewer.LocalReport.ReportEmbeddedResource = reportName;
IList<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("myParameterName", "myParameterValue"));
viewer.LocalReport.SetParameters(parameters);
viewer.RefreshReport();
Note: I took this code from a project where I am using it in a slight different context, so some code could be not necessary in your context.
That xxxx is simply the name of the Datasource that you want to have. it can be anything and is used to by the constructor to Construct a named data source. Its simply an identifier . Like pass "Merchent_Redemptions" or whatever u like.
The datatable is being used as a constructor rather it should be written as an index..
Below is the code present
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables(0));
The code should be in this format
ReportDataSource datasource = new ReportDataSource(xxxx, newDataSet.Tables[0]);
If u have dataAdapator, DataSet then try this on form load:-
this.DataTableAdapter.Fill(this.myDatabase_DataSet.tableName, parameter01, parameter02);
this.reportViewer1.RefreshReport();

Categories