How to fill subreport in crystal report aspx with dataset - crystal-reports

I have made two queries in dataset, then I want to set that query to the report
the first query is for the main report,
and the second query is for the subreport which have show by one of attribute field in main report.
Like I will show data (with where : from attribute field from main report)
Please anyone help me...
^^ but this code is still wrong

ReportDocument RptDocument = new ReportDocument();
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = "Your Dataset";
CrystalReportViewer1.DisplayGroupTree = false;
ds.Tables[0].TableName = "Main Report";
RptDocument.Load(Server.MapPath("your rpt file path"));
RptDocument.SetDataSource(ds.Table[0]);
RptDocument.Subreports[0].SetDataSource(ds.Tables[1]);
CrystalReportViewer1.ReportSource = RptDocument;
CrystalReportViewer1.DataBind();
CrystalReportViewer1.Visible = true;
}
please refer this code

Related

Need clarification about how to apply a custom update to data adapter source

I have created a record-view form that contains a few bound elements via a BindingSource and a BindingNavigator. The viewing of the data fields is operating correctly. Note that the variables da and ds are global in this form.
private void frmItem_Load(object sender, EventArgs e) {
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["myitems"].ToString();
da = new SqlDataAdapter("Select * From myitems where id > 0 ", scon);
ds = new DataSet();
da.Fill(ds);
bindingSource1.DataSource = ds.Tables[0];
bindingNavigator1.BindingSource = this.bindingSource1;
this.txtId.DataBindings.Add(new Binding("Text", bindingSource1, "id", true));
this.txtItem.DataBindings.Add(new Binding("Text", bindingSource1, "item", true));
this.txtUpdatedwhen.DataBindings.Add(new Binding("Text", bindingSource1, "updatedwhen", true));
}
I am showing this record-view form from a data grid view of items by using a row header mouse dbl-click event. The requested row from the dgv is correctly being selected and its row data is correctly being shown in the record-view form.
private void dgvItems_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
frmItem gfrmItem = new frmItem();
string sID = this.dgvItems.CurrentRow.Cells[0].Value.ToString();
gfrmItem.FilterByID(sID);
gfrmItem.Show();
}
I've added a save button to the navigator so that I can make individual record save. What I'm attempting to do is programatically apply a date/time stamp update before the record is saved from the button click.
private void btnSave_Click(object sender, EventArgs e)
{
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
da.Update(ds);
}
Although the date/time value is changed per the code and shows in the form, the update is not applying the date/time change.
I thought that the textbox value was being bound to the underlying dataset and would accept changes as if I had entered it manually ... but this is not occurring. I had read some other posts that using the data adapter update is the right way to go about this as apposed to doing something like performing a direct sql update.
I'm stumped with how to resolve this. Any pointers would be greatly appreciated.
After letting this sit a while and coming back to it today, I found a resolution.
There was a common misunderstanding at work that I saw in other posts.
That was that the dataadapter does not automatically populate its commands, even if you pass an active connection into the creation step.
So my resolution was to create a global SqlCommandBuilder variable along with the other ones I was using
SqlDataAdapter da;
SqlConnection sc;
SqlCommandBuilder sb;
DataSet ds;
then create the builder object at form load and initialize the update command into a string variable ... which isn't used there after, but the dataadapter commands are now populated.
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["networkadmin"].ToString();
sc = new SqlConnection(scon);
sc.Open();
string sSelect = "Select * From datatable where id > 0 Order By fld1;";
}
this.da = new SqlDataAdapter(sSelect, sc);
sb = new SqlCommandBuilder(da);
// This initiates the commands, though the target var is not used again.
string uCmd = sb.GetUpdateCommand().ToString();
this.ds = new DataSet();
this.da.Fill(this.ds);
Then the update step does work as expected:
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
DataRowView current = (DataRowView)bindingSource1.Current;
current["updatedwhen"] = this.txtUpdatedwhen.Text;
bindingSource1.EndEdit();
this.da.Update(ds);
I hope this helps someone.

Sub report text fields right alignment not working on jasper master report at run time

I set right alignment in sub report text fields. Its showing in preview report but when I run this report from java then sub report text fields right alignment are not working.
Here is my java code
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn=DriverManager.getConnection("jdbc:sqlserver://XYZ-BD-BBI01;user=abc;password=1234;database=myDataTables");
String report="C:\\Users/mainReport.jrxml";
JasperDesign jd = JRXmlLoader.load(report);
String sql = "select * from Report where ReportID = " + reportID;
JRDesignQuery query = new JRDesignQuery();
query.setText(sql);
jd.setQuery(query);
JasperReport jr = JasperCompileManager.compileReport(jd);
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("ReportID",1211);
JasperPrint jp1 = JasperFillManager.fillReport(jr, parameters, conn);
JasperViewer.viewReport(jp1, false);
}catch (Exception ex) {
ex.printStackTrace();
}
This is the current output
And I want this output

Populating unbound field in crystal report

I have a crystal report with these fields:
-Name
-Other
The field 'Other' is not a database field, so I added it as an unbound field.
Then I have this code in my controller:
DataSet ds = new DataSet();
DataTable dt = new DataTable("Product");
dt.Columns.Add("Name");
dt.Columns.Add("Other");
When I have populated the above datatable I add it to the dataset, anf then set the dataset as report's datasource:
ReportDocument report = new ReportDocument();
string reportFile = Server.MapPath("~/") + "\\bin\\Reports\\MyReport.rpt";
report.Load(reportFile);
report.SetDataSource(ds);
Then I set the export options (it's a excel report).
In my report I'm getting the text for the 'Name' field correctly, but the 'Other' field is empty. How can I associate the column from the datatable to this field?
Thanks in advance.
This is aspx File :
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" EnableParameterPrompt="false"
ReuseParameterValuesOnRefresh="true" EnableDatabaseLogonPrompt="False" ToolPanelView="None"
HasToggleParameterPanelButton="false" HasCrystalLogo="False" />
This is Cs File ......
protected void btnSubmit_Click(object sender, EventArgs e)
{
LoadData();
}
protected void LoadData()
{
DataSet ds= null;
ds = new DataSet();
DataTable dt = new DataTable("Product");
dt.Columns.Add("Name");
dt.Columns.Add("Other");
rptDoc.Load(Server.MapPath("~/bin/Reports/MyReport.rpt"));
rptDoc.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rptDoc;
CrystalReportViewer1.DataBind();
CrystalReportViewer1.refreshreport();
}
Try this code.......
try this with VB
'pass texbox2 to unbounddate1
CrystalReportSource1.ReportDocument.DataDefinition.FormulaFields.Item("unbounddate1").Text = "'" & Me.TextBox2.Text & "'"
'pass texbox3 to unbounddate2 CrystalReportSource1.ReportDocument.DataDefinition.FormulaFields.Item("unbounddate2").Text = "'" & Me.TextBox3.Text & "'"

How to merge two pdf documents into a single report in JasperReports?

I am new to JasperReports. I can create a simple PDF document with Javabean datasource. In my project I have created two separate pdf document with separate javabean datasource. Now I want to merge both documents into a single document. Can anyone tell me how to merge both documents into single document using JasperReports?
unfortunately the solution is build a sub report and use the 2 different DataSource or what ever connection you used
but there is an easy way to get over with this question :D
just simple no new reports ..... VoilĂ 
ok lets do it
JasperPrint jp1 = JasperFillManager.fillReport(url.openStream(), parameters,
new JRBeanCollectionDataSource(inspBean));
JasperPrint jp2 = JasperFillManager.fillReport(url.openStream(), parameters,
new JRBeanCollectionDataSource(inspBean));
ok we have over 2 records ..lets take our first record jp1 and add jp2 content into it
List pages = jp2 .getPages();
for (int j = 0; j < pages.size(); j++) {
JRPrintPage object = (JRPrintPage)pages.get(j);
jp1.addPage(object);
}
JasperViewer.viewReport(jp1,false);
This work like a charm .. with couple of loops you can merge any number of report together .. without creating new reports
http://lnhomez.blogspot.com/2011/11/merge-multiple-jasper-reports-in-to.html
You can use subreports for this. You dont have to recreate your current reports.
Create a master report, with 0 margins. Add all your reports to this as subreport and put condition that if datasource is available for this, only then print this report.
Now put all your individual datasources into one map data source and pass this datasource to master report.
Configute all subreports to the key in the map.
You can use use a list of JasperPrint like this:
List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
jasperPrintList.add(JasperFillManager.fillReport("Report_file1.jasper", getReportMap(1), new JREmptyDataSource()));
jasperPrintList.add(JasperFillManager.fillReport("Report_file2.jasper", getReportMap(2), new JREmptyDataSource()));
jasperPrintList.add(JasperFillManager.fillReport("Report_file3.jasper", getReportMap(3), new JREmptyDataSource()));
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("Report_PDF.pdf"));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setCreatingBatchModeBookmarks(true);
exporter.setConfiguration(configuration);
exporter.exportReport();
Multiple Pages in one JasperPrint
Sample Code:
DefaultTableModel dtm = new DefaultTableModel(new Object[0][3], new String[]{"Id","Name","Family"});
String[] fields= new String[3];
boolean firstFlag=true;
JasperPrint jp1 =null;
JasperPrint jp2 =null;
for (int i=0 ; i<=pagesCount ; i++)
{
fields[0]= "id";
fields[1]= "name";
fields[2]= "family";
dtm.insertRow(0, fields);
try
{
Map<String, Object> params = new HashMap<String, Object>();
if (firstFlag)
{
jp1 = JasperFillManager.fillReport(getClass().getResourceAsStream(reportsource), params, new JRTableModelDataSource(dtm));
firstFlag=false;
}else
{
jp2 = JasperFillManager.fillReport(getClass().getResourceAsStream(reportsource), params, new JRTableModelDataSource(dtm));
jp1.addPage(jp2.getPages().get(0));
}
}catch (Exception e)
{
System.out.println(e.fillInStackTrace().getMessage());
}
}
JasperViewer.viewReport(jp1,false);
Lahiru Nirmal's answer was simple and to the point. Here's a somewhat expanded version that also copies styles and other things (not all of which I'm positive are crucial).
Note that all of the pages are of the same size.
public static JasperPrint createJasperReport(String name, JasperPrint pattern)
{
JasperPrint newPrint = new JasperPrint();
newPrint.setBottomMargin(pattern.getBottomMargin());
newPrint.setLeftMargin(pattern.getLeftMargin());
newPrint.setTopMargin(pattern.getTopMargin());
newPrint.setRightMargin(pattern.getRightMargin());
newPrint.setLocaleCode(pattern.getLocaleCode());
newPrint.setName(name);
newPrint.setOrientation(pattern.getOrientationValue());
newPrint.setPageHeight(pattern.getPageHeight());
newPrint.setPageWidth(pattern.getPageWidth());
newPrint.setTimeZoneId(pattern.getTimeZoneId());
return newPrint;
}
public static void addJasperPrint(JasperPrint base, JasperPrint add)
{
for (JRStyle style : add.getStyles())
{
String styleName = style.getName();
if (!base.getStylesMap().containsKey(styleName))
{
try
{
base.addStyle(style);
}
catch (JRException e)
{
logger.log(Level.WARNING, "Couldn't add a style", e);
}
}
else
logger.log(Level.FINE, "Dropping duplicate style: " + styleName);
}
for (JRPrintPage page : add.getPages())
base.addPage(page);
if (add.hasProperties())
{
JRPropertiesMap propMap = add.getPropertiesMap();
for (String propName : propMap.getPropertyNames())
{
String propValue = propMap.getProperty(propName);
base.setProperty(propName, propValue);
}
}
if (add.hasParts())
{
PrintParts parts = add.getParts();
Iterator<Entry<Integer, PrintPart>> partsIterator = parts.partsIterator();
while (partsIterator.hasNext())
{
Entry<Integer, PrintPart> partsEntry = partsIterator.next();
base.addPart(partsEntry.getKey(), partsEntry.getValue());
}
}
List<PrintBookmark> bookmarks = add.getBookmarks();
if (bookmarks != null)
for (PrintBookmark bookmark : bookmarks)
base.addBookmark(bookmark);
}
Then, to use it:
JasperPrint combinedPrint = createJasperReport("Multiple Reports",
print1);
for (JasperPrint addPrint : new JasperPrint[] { print1, print2, print3 })
addJasperPrint(combinedPrint, addPrint);
// Now do whatever it was you'd do with the JasperPrint.
String combinedXml = JasperExportManager.exportReportToXml(combinedPrint);
I see JasperReports now has a newer "Report Book" feature that might be a better solution, but I haven't used one yet.

Crystal report xi + c#.net document load problem

I have a crystal report which gives me undefined error when opening document, does any one come across this type of error, below is the coding:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
///create instance of class first
ReportDocument rpDoc = new ReportDocument();
///load the report
rpDoc.Load(#"TicketingBasic.rpt");////------->>>problem is here
///pass the report to method for dataInfo
getDBInfo(rpDoc);
/// et the source for report to be displayed
CrystalReportViewer1.ReportSource = rpDoc;
}
protected static void getDBInfo(ReportDocument rpDoc)
{
///Connection Onject
ConnectionInfo cn = new ConnectionInfo();
///DataBase,Table, and Table Logon Info
Database db;
Tables tbl;
TableLogOnInfo tblLOI;
///Connection Declaration
cn.ServerName = "???????????";
cn.DatabaseName = "??????????";
cn.UserID = "?????????";
cn.Password = "????????????";
//table info getting from report
db = rpDoc.Database;
tbl = db.Tables;
///for loop for all tables to be applied the connection info to
foreach (Table table in tbl)
{
tblLOI = table.LogOnInfo;
tblLOI.ConnectionInfo = cn;
table.ApplyLogOnInfo(tblLOI);
table.Location = "DBO." + table.Location.Substring(table.Location.LastIndexOf(".") + 1);
}
db.Dispose();
tbl.Dispose();
}
}
Final code snippet is:
rpDoc.Load(Server.MapPath(#"TicketingBasic.rpt"));
Thank you all for the help.
The problem I am having now is report not printing or exporting to other types like .pdf,.xsl, .doc etc, any clue
so the error is literally "undefined error"? never seen that one before.
First guess is that you need the full physical path to the report.
rpDoc.Load(Server.MapPath(#"TicketingBasic.rpt"));
HttpServerUtility.MapPath
How are you handling the report outout?
When we do reports we set the file name:
ReportSource.Report.FileName = FileName;
Where filename is a string that is the name of the file (obviously). Then we select the report tables and export in whatever format. Try this.