Thursday, February 25, 2010

Crystal Report with Asp.NET – Using Data Objects

image
Customer.cs file


public class Customer
{
public int Year { get; set; }
public String Name { get; set; }
}


Then go to query editor and run this SQL, It is better you have some records inserted in the table.













image

SELECT TOP (1) Name, Year
FROM Table1
FOR XML AUTO, Elements



It will return following kind of a XML. thus copy it and save it as Table1.xml (for that add a new XML file to the project and paste the content and save it.)







<?xml version="1.0" encoding="utf-8" ?>
<Table1>
<Name>Amal</Name>
<Year>12</Year>
</Table1>



Then add a new crystal report by selecting a black report option.

















image

 image


Now go to the database Expert and select .Net Object from the Tree menu.













image image


In there select the Customer (this is the class which we created early) and click it to push the other category. Then It will popup following screen. In there select the table1.xml that we created early.



image If you click finished auto generated report will be appear. You also can customize your report as relevant.



imageNow you want to put the data to the report.  Thus add a web form to your project and named it as Report.aspx.  and drag and drop a crystal report viewer to the page.



Report.aspx



<html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title></title></head>
<
body><form id="form1" runat="server"> <div> <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
AutoDataBind="true" />
</
div>
</
form>
</
body>
</
html>


Report.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
List<Customer> cutomerlist = getCustomers();
ReportDocument report = new ReportDocument();
report.Load(Server.MapPath("CrystalReport.rpt"));
report.SetDataSource(cutomerlist);
CrystalReportViewer1.ReportSource = report;
}

private List<Customer> getCustomers()
{
// Put your data base code here to get customers
// I'm adding sample data here
List<Customer> list = new List<Customer>();
list.Add(new Customer() { Name = "Saman", Year = 12 });
list.Add(new Customer() { Name = "Brao", Year = 15 });
return list;
}
Post a Comment