You are on page 1of 19

Ngun: congdongcviet.

com Cn bn crystal reports trong lp trnh C#


Hm nay tui s dnh vit my bi tut c bn nht v crystal reports! u tin, ta to 1 database nh lm vic vi n, cc bn to trong sqlserver 1 database c tn l example, c 3 table l OrderMaster , OrderDetails ,Product
PHP Code:

USE [example] GO /****** Object: Table [dbo].[OrderMaster] Script Date: 09/04/2009 15:11:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[OrderMaster]( [OrderMaster_id] [int] NOT NULL, [OrderMaster_date] [datetime] NULL, [OrderMaster_customername] [varchar](50) NULL, [OrderMaster_createduser] [varchar](50) NULL, CONSTRAINT [PK_OrderMaster] PRIMARY KEY CLUSTERED ( [OrderMaster_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO /****** Object: Table [dbo].[OrderDetails] Script Date: 09/04/2009 15:11:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[OrderDetails]( [OrderDetails_id] [int] NOT NULL, [OrderDetails_masterid] [int] NULL, [OrderDetails_productid] [int] NULL, [OrderDetails_qty] [int] NULL, CONSTRAINT [PK_OrderDetails] PRIMARY KEY CLUSTERED ( [OrderDetails_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS ) ON [PRIMARY] GO /****** Object: Table [dbo].[Product] Script Date: 09/04/2009 15:11:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Product]( [Product_id] [int] NOT NULL, [Product_name] [varchar](50) NULL, [Product_price] [numeric](18, 0) NULL, CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED ( [Product_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO To 1 project winform application trong VS. Vo menu PROJECT-->Add New Item. Chn item l Crytal Report Hin ra 1 bng chn mu bo co, y ti s mc nh

= ON, ALLOW_PAGE_LOCKS

= ON) ON [PRIMARY]

= ON, ALLOW_PAGE_LOCKS

= ON) ON [PRIMARY]

= ON, ALLOW_PAGE_LOCKS

= ON) ON [PRIMARY]

Tip n l chn kt ni ti database ( y l example), ti s dng OLEDB Connection kt ni. Chn OLEDB connection hp thoi Create New Connection

in cc thng tin kt ni vo :

hp thoi k tip s hin cc thng s kt ni, c vic Finish y ti mun hin th table Product, nn chn table Product

Chn cc trng ca table product

Chn next v chn cc kiu hnh thc ca report, cui cng l Finish

xong bc to report, trn Form1 chng ta to lc ny,ko v 1 ci Button v 1 ci CrystalReportViewer control,khi click v button th s hin ra bo co :
PHP Code:

ReportDocument cryRpt = new ReportDocument(); cryRpt.Load(@"C:\Documents and Settings\Qu@n Bom\My Documents\Visual Studio 2008\Projects\Example\Example\CrystalReport1.rpt"); crystalReportViewer1.ReportSource = cryRpt; crystalReportViewer1.Refresh(); Qun, nh l phi using CrystalDecisions.CrystalReports.Engine;

__________________ Cnh Chym mi

dieu cay555 Xem H s cng khai Gi mt tin nhn ti dieucay555 Tm ton b bi vit bi dieucay555 #2 04-09-2009, 04:08 PM

dieucay555

Anonymous Member

Ngy gia nhp: 11 2007 Ni : Bit lm g? Bi vit: 950

To reports t nhiu bng


Bi trn ta to report ch vi 1 bng l Product, by gi s to report vi nhiu bng xem sao nh Mi vic cng ging nh trn, n bc chn cc table th ta chn c 3 table cho n mu , sau y l chn cc fields mun report :

Mi chuyn li tip tc nh th P/s : bi hng dn vn cha ht nn mng cc bn cha hi y, tm thi tui s lock ti li vit tip __________________ Cnh Chym mi
c chnh sa ln cui bi dieucay555 : 04-09-2009 lc 04:12 PM. dieu cay555 Xem H s cng khai Gi mt tin nhn ti dieucay555 Tm ton b bi vit bi dieucay555 #3 04-09-2009, 11:27 PM

dieucay555

Anonymous Member

Ngy gia nhp: 11 2007 Ni : Bit lm g? Bi vit: 950

S dng parameter trong crytal report


bi ny ti s hng dn cch s dng String parameter. V d,bn mun a vo 1 tham s l customername,v s hin ra cc n t hng ca khch hng report. y, tui s s dng tip ci report to bi trn. Chn Fields Explorer (menu Crytal Reports ->Fields Explorer),chut phi vo Parameter Fields,ri new,in cc tham s vo :

Ti chn kiu l string, cc kiu khc lm cng tng t Sau khi to xong parameter, ta s to biu thc cho cc fields,vo ca s design ca crytal reports ri lm nh hnh :

Hin ra 1 editor bn thit k fomular, mun s dng field no th chn field ,cc bn c lm theo th t t onh s trong hnh nh

Thit k form nh trong hnh :

Bi gi ta vit code cho s kin ca nt show Visual C# Code: La chn code | n/Hin code private void button1_Click(object sender, EventArgs e) { ReportDocument cryRpt = new ReportDocument(); cryRpt.Load(@"C:\Documents and Settings\Qu@n Bom\My Documents\Visual Studio 2008\Projects\Example\Example\CrystalReport1.rpt"); ParameterFieldDefinitions crParameterFieldDefinitions; ParameterFieldDefinition crParameterFieldDefinition; ParameterValues crParameterValues = new ParameterValues(); ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue(); crParameterDiscreteValue.Value = textBox1.Text; crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields; crParameterFieldDefinition = crParameterFieldDefinitions["Customername"]; crParameterValues = crParameterFieldDefinition.CurrentValues; crParameterValues.Clear(); crParameterValues.Add(crParameterDiscreteValue); crParameterFieldDefinition.ApplyCurrentValues(crParameterValues); crystalReportViewer1.ReportSource = cryRpt; crystalReportViewer1.Refresh(); } Cc file nh km Example.rar (62.3 KB, 2191 ln xem) __________________ Cnh Chym mi
dieu cay555 Xem H s cng khai Gi mt tin nhn ti dieucay555 Tm ton b bi vit bi dieucay555 #4 05-09-2009, 08:48 AM

dieucay555
Anonymous Member

Ngy gia nhp: 11 2007 Ni : Bit lm g? Bi vit: 950

To reports t DataSet
My bi trc tui ch to report t database, bi ny tui s to 1 report t DataSet coi sao nh . To 1 project winform mi, add thm vo 1 DataSet,gi nguyn cc thng tin mc nh ca n,trn DataSet ta to ra 1 datatable c 2 column l ID v Item :

By gi ta s to 1 report t DataSet mi to ra. Vo menu Project->Add new item, chn crytal report nh my ci trn kia, cc thng s mc nh lun cho tin. Nhng y ta ko to ra connect ti database no m chn lun dataset lc ny :

bc k tip, chn lun c 2 column ca DataTable trn DataSet lc ny nh

By gi to thm vo form 1 ci button v 1 crystalReportViewer control nh my ci trc. Tui s to d liu n gin cho dataset v hin th report : Visual C# Code: La chn code | n/Hin code private void button1_Click(object sender, EventArgs e) { DataSet1 ds = new DataSet1();

DataTable t = ds.Tables.Add("Items"); t.Columns.Add("id", Type.GetType("System.Int32")); t.Columns.Add("Item", Type.GetType("System.String")); DataRow r; int i = 0; for (i = 0; i <= 9; i++) { r = t.NewRow(); r["id"] = i; r["Item"] = "Item" + i; t.Rows.Add(r); } CrystalReport1 objRpt = new CrystalReport1(); objRpt.SetDataSource(ds.Tables[1]); crystalReportViewer1.ReportSource = objRpt; crystalReportViewer1.Refresh(); } __________________ Cnh Chym mi
dieu cay555 Xem H s cng khai Gi mt tin nhn ti dieucay555 Tm ton b bi vit bi dieucay555 #5 05-09-2009, 09:17 AM

dieucay555
Anonymous Member

Ngy gia nhp: 11 2007 Ni : Bit lm g? Bi vit: 950

To reports t Sql query


bi ny tui s to report t kt qu ca cc query trong Sql, vn s dng DataSet. Tui s to report cho bng Product trong ci database ni bi trn cng nh,cu truy vn ca chng ta nh sau :
PHP Code:

sql = "SELECT Product_id,Product_name,Product_price FROM Product"; To mi 1 project winform v add vo 1 DataSet mi,trn DataSet to thm 1 DataTable, v trn DataTable ta add 3 column vo nh

Tung t nh bi va trn, tui s to thm 1 crytal report v vn s dng ProjectData :

bc k tip tui s chn c 3 fields Product_id,Product_name,Product_price. xong phn thit k report Theo truyn thng, ta lai to 1 button v 1 crytalReportViewer nh my ci trn kia nh Visual C# Code: private void button1_Click(object sender, EventArgs e) { SqlConnection cnn; string connectionString = null; string sql = null; connectionString = "server=.\\sqlexpress;database=example;integrated security=true"; cnn = new SqlConnection(connectionString); cnn.Open(); sql = "SELECT Product_id,Product_name,Product_price FROM Product"; SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn); DataSet1 ds = new DataSet1(); dscmd.Fill(ds, "Product"); MessageBox.Show(ds.Tables[1].Rows.Count.ToString()); cnn.Close(); CrystalReport1 objRpt = new CrystalReport1(); objRpt.SetDataSource(ds.Tables[1]); crystalReportViewer1.ReportSource = objRpt; crystalReportViewer1.Refresh(); } __________________ Cnh Chym mi
dieu cay555 Xem H s cng khai Gi mt tin nhn ti dieucay555 Tm ton b bi vit bi dieucay555 #6 05-09-2009, 11:20 AM

La chn code | n/Hin code

dieucay555

Anonymous Member

Ngy gia nhp: 11 2007 Ni : Bit lm g? Bi vit: 950

To dynamic reports trong C#


My bi trc, chng ta to report t nhng database c chn sn, by gi ta to report t kt qu ca cc query SQL lc runtime. Ta cng to project winform v cng thm vo 1 DataSet nh bi trn kia nhng ko kt ni vo database no c. Trn Dataset, ta cng thm 1 datatable vo DataSet , trn Datatable ta to my ci column nh sau:

To thm 1 ci crytal report nh ba trc! Cc bn thc hin nh cc bc cc bi trn t lm, cng s dng ProjectData v chn tt c cac column ca ci Datatable va to nh.

Bi gi ta s thit k 1 ci Form nh bn gii,report s ph thuc vo cac queyry lc runtime:

Vit 1 hm x l cho cc query nhp vo : Visual C# Code:

public string procesSQL() { string sql = null; string inSql = null; string firstPart = null; string lastPart = null; int selectStart = 0; int fromStart = 0; string[] fields = null; string[] sep = { "," }; int i = 0; TextObject MyText ; inSql = textBox1.Text; inSql = inSql.ToUpper(); selectStart = inSql.IndexOf("SELECT"); fromStart = inSql.IndexOf("FROM"); selectStart = selectStart + 6; firstPart = inSql.Substring(selectStart, (fromStart - selectStart)); lastPart = inSql.Substring(fromStart, inSql.Length - fromStart); fields = firstPart.Split(','); firstPart = ""; for (i = 0; i <= fields.Length - 1; i++) { if (i > 0) { firstPart = firstPart + ", " + fields[i].ToString() + " AS COLUMN" + (i + 1); firstPart.Trim(); MyText = (TextObject) objRpt.ReportDefinition.ReportObjects[i+1]; MyText.Text = fields[i].ToString(); } else {

La chn code | n/Hin code

firstPart = firstPart + fields[i].ToString() + " AS COLUMN" + (i + 1); firstPart.Trim(); MyText = (TextObject)objRpt.ReportDefinition.ReportObjects[i+1]; MyText.Text = fields[i].ToString();

} } sql = "SELECT " + firstPart + " " + lastPart; return sql; } V vit code cho s kin ca button : Visual C# Code: private void button1_Click(object sender, EventArgs e) { SqlConnection cnn ; string connectionString = null; string sql = null; connectionString = "data source=SERVER NAME;initial catalog=crystaldb;user id=USER NAME;password=PASSWORD;"; cnn = new SqlConnection(connectionString); cnn.Open(); sql = procesSQL(); SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn); DataSet1 ds = new DataSet1(); dscmd.Fill(ds, "Product"); objRpt.SetDataSource(ds.Tables[1]); crystalReportViewer1.ReportSource = objRpt; crystalReportViewer1.Refresh(); } cc bn nh using my ci namespace cn thit nh Cn 1 iu na l mi vi d u dng database bi u,khi chy v d th cc bn nh chnh li chui kt ni cho ph hp Cc file nh km Example3.rar (97.9 KB, 1217 ln xem) __________________ Cnh Chym mi
dieu cay555 Xem H s cng khai Gi mt tin nhn ti dieucay555 Tm ton b bi vit bi dieucay555 #7 05-09-2009, 11:49 AM

La chn code | n/Hin code

dieucay555
Anonymous Member

Ngy gia nhp: 11 2007 Ni : Bit lm g? Bi vit: 950

To reports t XML
Ny gi ta mi ch to report t database truyn thng, gi s chi vi 1 kiu d liu hin i hn l XML cho n mu Tht ra, s khc nhau l khng nhiu, ch khc l khi ta design report th lc chn data s l XML. Cc bn to 1 file XML l Produc.XML : XML Code:

<?xml version="1.0" encoding="utf-8"?> <DataSet1 xmlns="http://tempuri.org/DataSet1.xsd"> <Product> <Product_ID>1</Product_ID> <Product_Name>Product1</Product_Name> <Product_Price>10</Product_Price> </Product> <Product> <Product_ID>2</Product_ID> <Product_Name>Product2</Product_Name> <Product_Price>12</Product_Price> </Product> <Product> <Product_ID>3</Product_ID> <Product_Name>Product3</Product_Name> <Product_Price>15</Product_Price> </Product> <Product> <Product_ID>4</Product_ID> <Product_Name>Product4</Product_Name> <Product_Price>5</Product_Price> </Product> <Product> <Product_ID>5</Product_ID> <Product_Name>Product5</Product_Name> <Product_Price>7</Product_Price> </Product> </DataSet1> Khi design report, ta s chn Create new connection->ADO.NET ri chn n file XML ny nh, cng vic cn li ko khc g bi u tin :

La chn code | n/Hin code

__________________ Cnh Chym mi


dieu cay555 Xem H s cng khai Gi mt tin nhn ti dieucay555 Tm ton b bi vit bi dieucay555 #8 05-09-2009, 12:24 PM

dieucay555
Anonymous Member

Ngy gia nhp: 11 2007 Ni : Bit lm g? Bi vit: 950

Xut kt qu report ra Excel,PDF


c my bi trn cc bn chc nm c s s v crytal report ri, gi ni thm v vic trch xut ra cc nh dng ca Excel hoc PDF Cc bn c th s dng ExportOptions ty chnh cc nh dng trch xut Quay li bi u tin, ta thm 2 ci button na,sau khi to v hin th thnh cng report, ta c th export ra pdf hoc excel y l export ra 1 file excel (file test.xls s dc to C) Visual C# Code: try { ExportOptions CrExportOptions; DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions(); ExcelFormatOptions CrFormatTypeOptions = new ExcelFormatOptions(); CrDiskFileDestinationOptions.DiskFileName = "c:\\test.xls"; CrExportOptions = cryRpt.ExportOptions;

La chn code | n/Hin code

} catch (Exception ex) { MessageBox.Show(ex.ToString()); } Export ra pdf : Visual C# Code: try {

CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile; CrExportOptions.ExportFormatType = ExportFormatType.Excel; CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions; CrExportOptions.FormatOptions = CrFormatTypeOptions; cryRpt.Export();

La chn code | n/Hin code ExportOptions CrExportOptions; DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions(); PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions(); CrDiskFileDestinationOptions.DiskFileName = "C:\\test.pdf"; CrExportOptions = cryRpt.ExportOptions; { CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile; CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat; CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions; CrExportOptions.FormatOptions = CrFormatTypeOptions; } cryRpt.Export();

} catch (Exception ex) { MessageBox.Show(ex.ToString()); } , nh


PHP Code:

using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared;

[C#]Hng dn to Crystal Reports bng Dataset


T l bu chn
Gii thiu Hin ti c rt t bi ting vit hng dn v phn ny. creating Crystal Reports using C#.NET . To mt Crystal Reports trong C#.Net vi CSDL access SQL sercer lm tng t. To dataset u tin bn to 1 d n Sau Add New Item trong Project menu, bn add a Dataset Ging hnh bn di. Ngun bi vit: http://sinhvienit.net/@forum/showthread.php?t=16748

Gii thiu Hin ti c rt t bi ting vit hng dn v phn ny. creating Crystal Reports using C#.NET . To mt Crystal Reports trong C#.Net vi CSDL access SQL sercer lm tng t. To dataset

u tin bn to 1 d n Sau Add New Item trong Project menu, bn add a Dataset Ging hnh bn di.

Code:
String connString = @"Provider=Microsoft.Jet.OLEDB.4.0;_ Data Source=..\\..\\myDB.mdb;User ID=Admin;Password="; OleDbConnection conn = new OleDbConnection(connString); conn.Open(); string query = "SELECT studentID, firstName, lastName, birthDate, _ address, contactNo FROM studentInfo"; OleDbDataAdapter oleDA = new OleDbDataAdapter(query,conn);

To mt bo co dng Crystal Reports Sau khi tao xong dataset bn add a Crystal Report vo project bng cch Add New Item trong Project menu. Sau chn tn xut hin ri nhn nt ok.

Mn hnh s hin th nh sau bn chn mt nh ri n OK Sau chn table ri insert table phn ny c th khc so vi VB2005 nhng cng tng t thi!

sau chn cc fields hin th trong report > nhn nt add

Xong xu bn nhn nt next>cui cng chn style kiu bn mun report hin th

K tip bn s cho report hin th trn form

Bn tao mt form v add crystalReportViewer vit code trong thuc tnh page load

Code:
// code to get data from the DB DBConnection DBConn = new DBConnection(); OleDbDataAdapter myDataAdapter = DBConn.getDataFromDB(); // use the created Dataset to fill it with data got // from the DB by using the DataAdapter DataSet dataReport = new DataSet(); myDataAdapter.Fill(dataReport,"myPersonalInfoTable "); // create a new report from the created CrystalReport myDataReport myDataReport = new myDataReport(); // set the data source of the report myDataReport.SetDataSource(dataReport); // set the report source of the created crystalReportViewer // component to the created report crystalReportViewer1.ReportSource = myDataReport; bn c th thay i dng dn mt nh bng

Code:

crystalReportViewer1.ReportSource = @..\Reports\salesReport.rpt;
Xem trc mt bo co vi Window Form Sau khi to mt bn bo co trong bi trc (Bi 1) , gi bn c th xem n s dng c Window Form hoc ASP.NET . Trong bi ny ch hng dn xem n trong mt Window Form m thi Gi ta s sa i 1 Form c th xem c bo co m chng ta to . Khi bn to mt project mi th mt Form tn l Form1 lun c gn n project ca bn . Gi bn hy m design ca Form ny ln v thm vo control CrystalReportViewer .

Vi control ny bn c nhiu cch xem trc mt bo co . Trong v d ny ta s s dng thnh phn (component) ReportDocument bi v n d dng la chn . Bn thm thnh phn component ReportDocument n form bng cch double clicking vo n t Toolbox . Sau bn click phi chut vo Form ca bn (click vo control CrystalReportViewer m ta ko vo) chn Choose a Crystal Report . Mt ca s mi s hin ra trong hnh

Trong ca s ny khi bn s chn bo co cho Form ca bn . Gi bn c th xem kt qu ca mnh bng cch chy th Form va to v y l kt qu ca mnh .

Hnh nh ny b thay i kch thc nhm trnh lm v giao din. Bm vo y xem nh kch thc y ( 1019736 )

Thng Mi Mt 23, 2010 - ng bi lamjangvan | Crystal Report

You might also like