Sunday, September 20, 2009

How to Create a Crystal Report using Data sets in C#.NET

Assume that you already SQL server database created and table also. Following illustrate our table structure and data.

CustomerName InvoiceNum TotalAmount Paid Balance
Amal 10001S 1000.00 900.00 100.00
Amal 10002S 2500.00 2000.00 500.00
Amal 10003S 1800.00 1500.00 300.00
Amal 10004S 2500.00 2000.00 500.00
Nimal 10005S 3000.00 3000.00 0.00
Nimal 10006S 1000.00 1000.00 0.00
Nimal 10007S 1500.00 1500.00 0.00

First you need to have a data connection created. (Read ..How to create a Data Connection to SQL Server using Wizard) 

Then you need to have a Data set created. (Read .. How to Create a DataSet, DataTables, Table Adapter Using C#.NET Wizard)  In here I’m going to create a report with main data by customer name (CustomerName, InvoiceNum , TotalAmount) therefore i need a data table with relevant fields.

To add a Crystal Report go to Project –> Add new items –> Reporting –> CrystalReport.  Than give a name. In my example i gave a name as CustomerInfo.


Then above window will appear. In that select As a Black report and press next to proceed.  Then report design page will appear. First of all we need to set data sources relevant to  the report. Therefore i right click the database Field and go to Data Base Expert .. section.


In Database Expert window find the relevant data set under the Project data. And select the data table listed and add it to the report as follows.


Then finally drag and  drop relevant fields from database field  to details section and create your report and save it. If you want you can also give report headers , page numbers and etc.. by right click and inset text object.  


Now we are going to Load the report to our form using CrystalReport viewer. When the user enter the customer name and press select our report will be displayed.


private void btnView_Click(object sender, EventArgs e)
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.UserID = "sa";
cb.Password = "sa123";
cb.InitialCatalog = "CustomerInfo";

// Create SQL Connection
SqlConnection sc = new SqlConnection(cb.ConnectionString);

CusDataSetTableAdapters.CusMainTableAdapter Ta =
Ta.Connection = sc;
CusDataSet.CusMainDataTable Td = Ta.GetDataByName(txtCusName.Text);

// Create a Report
CustomerInfo Ci = new CustomerInfo();

crystalReportViewer1.ReportSource = Ci;


(Read… How to Create a Crystal Report Sub Report in C#.NET)

Post a Comment