The following content is the program code:
Before we studied Crystal Reports in VS.Net, my friend and I were very curious about how to add this complicated stuff to our web application. A week later, after reading a lot of "HOWTO" documents, we successfully added some simple reports to our Asp.net program and got some tips.
This article teaches you how to use Crystal Reports in .Net Web applications, and can also help you avoid detours in the learning process. In order to get the best results, readers should have some basic knowledge of Asp.Net database access and development experience using VS.Net.
Introduction
Crystal Reports can be obtained in many ways, one of which is to use VS.Net to create it, which provides a very rich model that allows us to operate properties and methods at runtime. If you are using VS.Net to develop .Net programs, then you do not need to install other software because it is already embedded in VS.Net.
advantage:
VS.Net Crystal Reports has the following main advantages:
Rapid report development
Ability to export into complex interactive charts
Can be used in WebForm with other controls
Able to dynamically export reports into .pdf, .doc, xls, html, rtf and other formats
structure:
Some components make up the two-tier structure of Crystal Reports. The required web applications are:
Client:
The client only needs a browser that can access the report embedded in the aspx page.
server:
- Crystal Report Engine (CREngine.dll)
It can complete some tasks, such as merging data in report files, converting reports to other formats, etc. It is precisely because of the reporting engine that Crystal Reports in Asp.Net can be converted into ordinary HTML format.
- Crystal Report Designer (CRDesigner.dll)
Crystal Reports are created in the designer, where you can design titles, insert data, formulas, charts, subreports, etc.
- .rpt report file
The first step in executing a report is to create this report in the Crystal Report Designer interface. Microsoft has provided some ready-made .rpt examples in the default installation.
- Data Source
The method of obtaining the database from the .rpt file depends on your choice of method. You can choose to let Crystal Reports select the data itself without using any code or you can choose to manually assemble the DataSet and then transfer it to the report file.
- Crystal Report Viewer web form Control (CRWebFormViewer.dll)
The Crystal Report View Control is a WebForm control, which can be regarded as a container that stores reports in an .aspx page. Note: In some complex operations, the report server and the Web server may not be on the same physical host, and the Web server transmits the HTTP request to the report server. Crystal Reports can also be executed as a WebService.
Fetching data from Crystal Reports in execution mode can be achieved using the following methods:
- Pull mode:
When requested, Crystal Reports directly connects to the database based on the specified driver and assembles the data.
- Push mode:
At this time, the development table has to write its own code to connect the data and assemble the DataSet, and transfer it to the report at the same time. In these cases, you can maximize report performance by using connection sharing and limiting the size of the record collection.
Report type:
Crystal Report Designer can include reports directly into the project or use independent report objects.
- Strongly-typed reports:
When you add a report file to a project, it becomes a "strongly-typed" report. In these cases, you will have the power to create the report object directly, which will reduce some code and can provide some performance.
- Un-Typed Report:
The reports here are not directly included in the project and are therefore called 'un-typed' reports. In this case, you have to create an instance using the "ReportDocuemt" object of Crystal Reports and use the report "manually".
Other things to note
- Although Crystal Report Viewer has some cool features like zooming, page navigation, etc. But it does not provide a printing function, you have to call the browser's printing function.
- If the Crystal Report in VS.Net is not registered, it can only be used 30 times. After 30 times, the "save" function can no longer be used. To avoid this, you should not register this product here at http://www.crystaldecisions.com/ . (This doesn’t seem to be the case. It seems to be able to use it for a long time without registering, but support cannot be provided)
- The default installation of Crystal Reports can only support 5 users. In order to support more users, you have to purchase a license at http://www.crystaldecisions.com/ .
Let's feel it - using a ready-made Crystal Report file in Asp.net 1) Drag the Crystal Report Viewer control (Crystal Report Viewer) from the WebForm toolbar to the .aspx page.
2) Call up the properties window of the Crystal Report Viewer control
3) Click the [...] button to view the "Data Binding" property, and the DataBinding window pops up.
4) Select "Report Source" from the "Bindable Properties" area on the left
5) Select the "Custom Binding Expression" radio button and specify the file name and path of the .rpt file in the bottom window on the right, for example: "C:\Program Files\Microsoft Visual Studio.NET\Crystal Reports\Samples\Reports\General Business\World Sales Report.rpt" and then "OK"
Note: The file "World Sales Report.rpt" file is created during the VS.Net installation. If you specified another directory during the installation process, you'd better confirm the correctness of the path at this time.
The above steps actually insert the following code into the Asp.Net file:
as well as:
id="CrystalReportViewer1"
runat="server" Width="350px" Height="50px"
ReportSource=''>
Note: The style generated by ReportSource in the code automatically generated in my VS.Net official version is not like this, it is:
ReportSource=""
This is wrong and an error message will appear. There are two errors:
It must be modified manually according to the format introduced in this article. This can be regarded as a bug of VS.Net.
6) Call the DataBind method in the Page_Load method. (Code is VB.Net)
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
DataBind()
End Sub
7) Save and compile your page. Now, you have a WebForm page with Crystal Reports embedded inside it.
Note: In actual development, there will be an error that the inetsrv directory cannot be accessed at the beginning. The solution is to change the security attributes of the directory so that the User user has writable permissions. Flying Knife I found that the solutions provided by the .Net system are useless, and it may be because I am using the Windows.Net operating system.
Using Crystal Reports in Asp.Net (Part 2)
www.dotnet8.com 2002-9-6 DotNet Bar
The following content is the program code:
Using Pull Mode We will use the following steps to execute Crystal Reports through Pull mode
1. First create the rpt file and use the Crystal Report design interface to set up some necessary data connections.
2. Drag and drop a CrystalReportViewer control to the aspx page, set its properties to specify the .rpt file we created in the previous step.
3. Call the DataBind method in the code.
Create .rpt file:
1) Right-click "Solution Browser" and select "Add"--"Add New Item"-->"Crystal Report" in the pop-up menu
2) Select the "As Blank Report" radio button in "Crystal Report Library" and finally click "OK".
3) The Crystal Report Designer will pop up here.
4) Right-click the "Details Area" in the report and select "Database" -> "Add/Delete Database..."
5) In the pop-up "Database Expert", expand the "OLE DB(ADO)" option, and another "OLE DB(ADO)" window will pop up.
6) In the "OLE DB (ADO)" pop-up window, select "Microsoft OLE DB Provider for SQL Server" and then "Next"
7) Specify the information server to connect to: ASPCN (write whatever the name of your machine is)
User ID: sa
password:
Database: Pubs
8) Click "Next" and finally click the "Finish" button.
9) At this time you can see the database we selected in the "Database Expert" window.
10) Expand the "Pubs" database, expand the "Table", select the "Stores" table and add it to the "Selected Tables" area, click the "OK" button.
11) Now in the "Field Resource Browser", the table you selected and the fields in the table will be displayed in the "Database Field" area on the left.
12) Drag and drop the required fields into the "Details" area of the report. The field names will automatically appear in the "Header" area. If you want to modify the header text, you can right-click the text in the "Header" area, select the "Edit Text Object" option and edit it.
13) Save so we have a Crystal Report file.
Create the CrystalReportViewer control
14) Return to the previous WebForm, drag and drop a Crystal Report Viewer control onto the page.
15) Call up the properties window of the Crystal Report Viewer control, select the "DataBindings" area and click [...]
16) In the "Crystal Report Viewer Data Binding Window", select "ReportSource" in the "Bindable Properties" on the right, and select the "Custom Binding Expression" in the lower right corner to specify the .rpt file path.
17) At this point you can see a preview of the report file composed of some virtual data from the Crystal Report Viewer control.
Note: In the above example, CrystalReportViewer can directly call the real data at design time because the data has been saved at this time. In this case, when the data is not saved at design time, it cannot display the data. Instead, some dummy data is displayed, and real data is selected only at execution time.
Code Behind Programming
18) Call the DataBind method in the Page_Load method.
execute your program
19) Create and run your program!
You can now use some built-in functions of Crystal Reports directly on the web page, such as page navigation, zoom, etc.
Using Crystal Reports in Asp.Net (Part 2)
www.dotnet8.com 2002-9-6 DotNet
[HTML] We use the following steps to execute Crystal Reports using Push mode:
1. Design a DataSet
2. Create a .rpt file and assign it to the DataSet created in the previous step.
3. Drag and drop a CrystalReportViewer control in the aspx page and connect it with the previous rpt file.
4. Access the database in code and store the data in the DataSet
5. Call the DataBind method.
Design a DataSet
1) Right-click "Solution Browser" and select "Add" -- "Add New Item" --> "Dataset"
2) Drag and drop the "Stores" table (located in the PUBS database) from "SQL Server" in "Server Explorer".
3) At this time, there will be a structure diagram of the Stores table in the data set.
- The .xsd file only contains a structure diagram, but there will be no data in it.
Create .rpt file:
4) Create this file using the method introduced above. The only difference is to use a data set instead of the previous direct connection data.
5) After creating the .rpt file, right-click "Details" --> "Add/Delete Database"
6) In the "Database Expert" window, expand "Project Data" (replacing the previous OleDb), expand "ADO.Net Data Set" -- "DataSet1", and select the "Stores" table.
7) Add the "Stores" table to the "Selected Tables" and click "OK"
8) Use the method in PULL mode to create a WebForm
Create a Crystal Report Viewer control
9) Create a Crystal Report Viewer control and set its properties. This is consistent with the PULL mode.
Code Behind code:
10) Use the following subfunction in the Page_Load method:
VB.Net code:
SubBindReport()
Dim myConnection As New SqlClient.SqlConnection()
myConnection.ConnectionString= "server= (local)NetSDK;database=pubs;Trusted_Connection=yes"
Dim MyCommand As New SqlClient.SqlCommand()
MyCommand.Connection = myConnection
MyCommand.CommandText = "Select * from Stores"
MyCommand.CommandType = CommandType.Text
Dim MyDA As New SqlClient.SqlDataAdapter()
MyDA.SelectCommand = MyCommand
Dim myDS As New Dataset1()
'This is the DataSet we use on design mode
MyDA.Fill(myDS, "Stores")
'You have to use the same name as your previous DataSet.
Dim oRpt As New CrystalReport1()
'Crystal report binding
oRpt.SetDataSource(myDS)
'Set the ReportSource of Crystal Report
CrystalReportViewer1.ReportSource = oRpt
End Sub
C# code:
private void BindReport()
{
string strProvider = "Server=(local);DataBase=pubs;UID=sa;PWD=";
CrystalReport1 oCR = new CrystalReport1();
Dataset1 ds = new Dataset1();
SqlConnection MyConn = new SqlConnection(strProvider);
MyConn.Open();
string strSel = "Select * from Stores";
SqlDataAdapter MyAdapter = new SqlDataAdapter(strSel,MyConn);
MyAdapter.Fill(ds,"stores");
oCR.SetDataSource(ds);
this.CrystalReportViewer1.ReportSource = oCR;
}
Note: In the above code, you have to note that oRpt is a "Strongly Typed" report file. If you need to use "UnTyped" reports, you have to use the ReportDocument object and then call the report file.
Run your program.
11) Run your program
Export report files to other formats
You can export report files to the following formats:
1. PDF (Portable Document Format)
1. 2. DOC (MS Word Document)
2. 3. XLS (MS Excel Spreadsheet)
3. 4. HTML (Hyper Text Markup Language – 3.2 or 4.0 compliant)
4. 5. RTF (Rich Text Format)
uses Pull mode to export reports. When exporting files created using Pull mode, Crystal Reports accurately opens the required data. The following is the code to perform the export function:
C# code:
VB.Net code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myReport As CrystalReport1 = New CrystalReport1()
'Note: Here we create a strong-typed Crystal Report instance.
Dim DiskOpts As CrystalDecisions.Shared.DiskFileDestinationOptions = New CrystalDecisions.Shared.DiskFileDestinationOptions()
myReport.ExportOptions.ExportDestinationType = CrystalDecisions.[Shared].ExportDestinationType.DiskFile
' This option is also needed when exporting to other files
' Such as Microsoft Exchange, MAPI, etc.
myReport.ExportOptions.ExportFormatType = CrystalDecisions.[Shared].ExportFormatType.PortableDocFormat
'Here we export it to a .pdf format file, you can also choose other types of files above
DiskOpts.DiskFileName = "c:Output.pdf"
'If you do not specify the exact directory, the file will be saved in the [Windows]System32 directory.
myReport.ExportOptions.DestinationOptions = DiskOpts
'Crystal Report files do not contain a direct FileName property, so you cannot directly specify the saved file name
'So you have to use the DiskFileDestinationOptions object and set its DiskFileName property
'For the path you want, finally specify the DestinationsOptions property of Crystal Reports as the DiskFileDestinationOption above
myReport.Export()
'The above code will do the exporting job.
End Sub
Export Crystal Reports using PUSH mode. When the exported report is created by PUSH mode, the first step is to establish a connection and assemble the DataSet through programming, and set the SetDataSource property of the report. The following steps are the same as in Pull mode.
[/HTML]
Summary of the use of Crystal Reports in the .NET environment
. Crystal Reports is an excellent report development tool. When I was developing a general management system, all reports used Crystal Reports. Its simplicity, ease of use and powerful functions made me love it more. Now I will Crystal Reports are presented to everyone using notes.
1. When using the built-in Crystal Report, please register, otherwise you can only use
the Crystal Report 30 times. Registration number: 6707437608
Password:AAP5GKS0000GDE100DS
2. Use CrystalReportViewer for preview.
The CrystalReportViewer control allows you to view the Crystal Report in the application. The ReportSource property sets which report to view. After this property is set, the report is displayed in the viewer. The report source can be a ReportDocument, the path of the report file, or a strongly typed report.
1. Open the "Toolbox" and drag a CrystalReportViewer onto the form, which we name rptVew.
2. Use drag-and-drop to resize the Windows Forms Viewer to the desired size and move it to the desired position.
3. When you run the application, the report will be displayed in the viewer.
3. Create a new report
1. Point to "Add" and click "Add New Item".
2. In the "Add New Item" dialog box, select Crystal Report from the "Template" area, name the report rptClient, and click "Open".
3. In the Crystal Report gallery, select one of the following options:
· Use Report Expert—Guides you through the report creation process and adds your selections to Crystal Report Designer.
· As a blank report—Opens Crystal Report Designer.
· From existing report—Creates a new report with the same design as another report you specify.
Note The Crystal Report library contains experts who can guide you through the creation of several specific types of reports. You may want to use an expert to create your initial report to determine which report construction method suits your needs.
4. Click the OK button.
If you choose to use Report Expert, the Report Expert dialog box appears with the Data Explorer. Select the required data for each folder, complete the operations on the Report Expert tab interface, and then click Finish to access Crystal Report Designer and your report
4. Do you need to set the data source dynamically?
Crystal Reports connects to the database through a database driver. Each driver is written to handle a specific database type or database access technology.
Pull and Push Models To provide developers with the most flexible data access methods, the Crystal Reports database driver is designed to provide both pull and push models of data access.
pull model
In the pull model, the driver will connect to the database and "pull" data in as needed. When using this model, both the connection to the database and the SQL commands executed to obtain the data are handled by Crystal Reports itself, without the need for developers to write code. Use the pull model if you don't need to write any special code at runtime.
push model
In contrast, the push model requires developers to write code to connect to the database, execute SQL commands to create a recordset or dataset that matches the fields in the report, and pass the object to the report. This method allows you to put connection sharing into your application and filter out the data before Crystal Reports receives it.
4. Make reports from ADO.NET data sets and
create data set objects from the database
1. Create a new schema file in the project:
a. In the solution explorer, right-click the project name, point to "Add", and then click " Add new item".
b. In the Categories area of the Add New Item dialog box, expand the folder, and then select Data.
c. Select Dataset in the Template area.
d. Accept the default name Dataset1.xsd.
This creates a new schema file (Dataset1.xsd) that will be used later to generate a strongly typed dataset. The schema file will appear in the ADO.NET Dataset Designer.
2. Specify the database location:
a. In Server Explorer, right-click Data Connections and select Add Connection.
b. In the Data Link Properties dialog box, click the Provider tab, and then select a provider (such as Microsoft OLE DB Provider for SQL Server).
c. Click the Connection tab and specify the location of your database. Enter your server and login information where required.
d. Click the OK button.
Your database and its tables and fields now appear in Server Explorer under the Data Connections node.
3. In Solution Explorer, double-click Dataset1.xsd (if it is not already the active view).
Dataset1.xsd should now appear in the Datasets tab.
4. To schema the dataset, drag the required tables from Server Explorer to the Datasets tab of Dataset1.xsd.
5. Click Save Dataset1.xsd to save the Dataset1.xsd file.
6. On the Generate menu, click Generate to generate the dataset object for the project.
The ADO.NET DataSet object provides a description of the data from which tables can be added to a Crystal report. Use the Database Expert in Crystal Report Designer to add tables from ADO.NET Dataset objects.
Please call the Database Expert when you use the Report Expert to create a new report. Or, to access the Database Expert from a report that has been created using ADO.NET, right-click in Report Designer, point to Databases, and then click Add/Remove Database.
Connect a report to an ADO.NET Dataset object
1. In Database Expert, expand the Project Data folder.
2. Expand the "ADO.NET Datasets" folder.
3. Select the required dataset object.
For example, if you are using a dataset object generated from the schema file "Dataset1.xsd" of project "WindowsApplication1", you should select "WindowsApplication1.Dataset1".
4. Select the tables to add to the report, just as you would with other data sources.
5. Code for dynamically changing data sources
Dim dsdataSet As New DataSet()
Dim oRpt As New rptClient() 'The established report rptClient
requires readers to fill in the data set dsdataSet by themselves
'Use the "report engine" object model to pass the filled data set to the report
oRpt.SetDataSource(dsdataSet. Tables(0))
'Bind the report object with data to the Windows Forms Viewer, rptVew (CrystalReportViewer control)
rptVew.ReportSource = oRpt
Note that the FillDataSet method can connect to the specified database, extract the data, and then disconnect the database . If you want to add multiple tables in the database to the report, use the SQL JOIN statement to join these tables together; then specify a result table in the FillDataSet method
6. Create a master-detail report
In the report, there are many reports Master-detail table structure, such as order and order product details, order is a record in one table, and entries are multiple records in another table. The two tables are related through a field. This kind of report can use its grouping Function implementation:
1. Create a new project
2. Add a CrystalReportViewer control to FORM1
3. Connect to the Northwind database on SQL SERVER 2000 in the service resource manager
4. Add a data set Dataset1 and add the Orders and Order Details are added to the data set.
5. Add a Crystal Report, use Report Expert, select "ADO.NET Data Set" in the project data, insert the tables Orders and Order Details, "Link" is the link to the associated field, select the field to be displayed in "Field" For the fields of the main table and detail table, the group selection basis in the group is the Orders table OrdersID field, total, chart, selection (can be filtered), style (can set the report title), and can be set by yourself. After setting up, click Finish.
6. Adjust the position, width, etc. of the fields to be displayed in the report designer.
7. Add code in the window.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim oRpt As New CrystalReport1()
Dim dsdataSet As New Dataset1()
Dim CN As New Data.SqlClient.SqlConnection("data source=PMSERVER;initial catalog=Northwind;user id=sa;password=sa")
CN.Open()
Dim daOrders As New Data.SqlClient.SqlDataAdapter("select * from orders", CN)
daOrders.Fill(dsdataSet, "orders")
Dim daDetails As New Data.SqlClient.SqlDataAdapter("select * from [Order Details]", CN)
daDetails.Fill(dsdataSet, "Order Details")
'Use the "Report Engine" object model to pass the populated data set to the report
oRpt.SetDataSource(dsdataSet)
CrystalReportViewer1.ReportSource = oRpt
End Sub
8. Run the program
7. Use a program to change the text in the report.
The code is as follows:
Dim GetTextObject As TextObject
' Get the ReportObject by name, convert it to TextObject, and return this object.
GetTextObject = orpt.ReportDefinition.ReportObjects.Item("text13")
GetTextObject.Text = "XXXX system"
Summary: Crystal Reports has very powerful functions. It can also export WORD, EXCEL, RTF and other files, and can also generate complex and beautiful charts. It is a powerful tool for WEB and WINDOWS report development.
(Part of the information in this article comes from MSDN)
Author: Li Honggen
E-MAIL: [email protected]
I have the following ideas:
1. Obtain SQL database related data through connection query;
2. Place it in DataSet;
3. Call Crystal Reports (linear or columnar template) to generate reports;
4. Output and generate EXCEL document.
Please tell me, heroes, how to implement the above ideas? (It would be better if there are examples)
Thank you so much!
-------------------------------------------------- -------------
1. Add a new project DataSet to your project, connect to the database, and add the required data tables or stored procedures
Drag into this DataSet and compile the DataSet
2. Use the Crystal Report that comes with Vs.net to create a report with DataSet as the data source.
3. Push data into this report in the program
4.Crystal Report has the option to output to Excel, which can also be achieved through a program.
Dim conn As SqlConnection
Dim da As SqlDataAdapter
Dim strSQL As String
conn = New SqlConnection()
conn.ConnectionString = "User ID=sa; PWD=1234;Data Source=xxxx; Initial Catalog =xxxxx"
conn.Open()
strSQL = "Select * from TableName"
da = New SqlDataAdapter(strSQL, conn)
Dim ds As New DataSet()
da.Fill(ds, "TableName")
Dim RptDoc As New ReportName()
RptDoc.SetDataSource(ds)
'Specify data for RptDoc,
CrystalView1.ReportSource = RptDoc 'Specify data for CrystalView
CrystalView1.DataBind()
conn.Close()
5. If you need to display fields associated with multiple tables, it is best to create a DataSet using a stored procedure.
-------------------------------------------------- -------------
Please refer to the following code:
string strconn=connection string;
SqlConnection myconn=new SqlConnection(strconn);
string strcmd=@"select statement";
SqlCommand mycmd=new SqlCommand(strcmd,myconn);
SqlDataAdapter myda=new SqlDataAdapter(strcmd,myconn);
DataSet myds=new DataSet();
myconn.Open();
myda.Fill(myds,"report name");
Report name myrpt =new report name();
myrpt.SetDataSource(myds);
this.CrystalReportViewer1.ReportSource=myrpt;
Export to EXCEL:
myrpt.ExportOptions.ExportDestinationType=CrystalDecisions.Shared.ExportDestinationType.DiskFile;
myrpt.ExportOptions.ExportFormatType=CrystalDecisions.Shared.ExportFormatType.Excel;
CrystalDecisions.Shared.DiskFileDestinationOptions opt=new CrystalDecisions.Shared.DiskFileDestinationOptions();
opt.DiskFileName=@"File Name";
myrpt.ExportOptions.DestinationOptions =opt;
myrpt.Export();
Chinese help download for Crystal Reports 9:
http://www.ourfly.com/download/download.aspx
http://www.enwell.net/soft/
http://www.fast8.com/news.asp
Crystal Reports for Visual Studio .NET
PictureObject members see
PictureObject class¦ CrystalDecisions.CrystalReports.Engine namespace public instance properties
Border(Inherited from ReportObject) Border. Get the Border object.
Height (inherited from ReportObject) Int32. Gets or sets the height of the object in twips.
Kind (Inherited from ReportObject) ReportObjectKind. Gets the type of report object.
Left (Inherited from ReportObject) Int32. Gets or sets the position of the upper left corner of the object in twips.
Name (inherited from ReportObject) String. Get the object name.
ObjectFormat (Inherited from ReportObject) ObjectFormat. Get the ObjectFormat object.
Top (Inherited from ReportObject) Int32. Gets or sets the top position of the object in twips.
Width (inherited from ReportObject) Int32. Gets or sets the width of the object in twips.
See
PictureObject
ClassImports CrystalDecisions.CrystalReports.Engine
Dim picObject As PictureObject
picObject = oRpt.ReportDefinition.ReportObjects.Item("picture1")
From: http://expert.csdn.net/Expert/topic/1896/1896874.xml?temp=.78677
When you use Crystal Reports based on webform, if you simply follow the "A Dao" method on the Internet, you will definitely be prompted. You: Login failed.
Regarding this problem, I spent a whole day studying the help file of Crystal Reports and finally got a solution.
I am not a conservative person. I believe that there are many netizens who are spending energy on researching this issue like me. I don’t want everyone to spend energy in vain like me.
Here are a few steps I took to implement this solution. Don't be anxious, it will be of great help to you if you read it slowly.
Step 1: Look at the sample file. Crystal Reports comes with a sample file, and the database is access (without password). I first ran the sample file (based on webform and winform) and the result showed the correct report, just like the "flying knife" example.
So, I created a report file and .aspx file myself, but the result showed that the login failed! But I changed the report file to the sample report file and no more errors occurred.
What's the problem? Could it be that the report format file has login permission settings? Through tracking and debugging, I compared and analyzed my report file and the sample report file, and found no difference. It seems that the problem is not in the report file.
Is it a database problem? When I created an access, the login failed!
Is it not a database problem (my own database has unpassworded access, and the same is true for the database in the help)? Isn't it a problem with the report format file (I carefully analyzed that the original codes of the two are the same)?
So where does the problem occur? I can't understand it!
Step 2: Find the help file So I asked for help again. I searched through the help of Crystal Reports and finally found the words "Access Secure Database [C#]" and found the following paragraph:
The process for accessing a secure database through Crystal Reports for Visual Studio .NET differs between Web Forms and Windows Forms. In Windows Forms, a dialog box automatically prompts the user for a username and password (the test succeeds easily). In Web Forms, you need to design a form to obtain this information from the user. In both cases, code can be used to specify usernames and passwords, providing the same level of security for all users of the application.
So I used the same database (first using the access database in the help example, and later using the access database I created). It is found that for the same report file, winform can show success, but webform still shows login failure! So I kind of understand what it means!
It seems that the problem lies in the permission settings.
Step 3: Research for help and finally succeed!
In the help, I found the words "Set Database Login Parameters", which provided some information that I later found to be very useful:
The following example shows how to pass login parameters into a report table. This example uses a connection to a secure SQL Server database.
Start a new project and add a Button and four TextBox controls to the form.
Name the Text Box controls: serverNameTxt, dbNameTxt, userNameTxt, and passwordTxt.
Double-click the Button control to specify the code for the Click event. Insert appropriate code based on the language used.
[C#]
// Declare the required variables.
TableLogOnInfo logOnInfo = new TableLogOnInfo ();
int i = 0;
// Loop through each table in the report.
for (i=0;i == Report.Database.Tables.Count - 1;i++)
{
//Set the connection information of the current table.
logOnInfo.ConnectionInfo.ServerName = serverNameTxt.Text;
logOnInfo.ConnectionInfo.DatabaseName = dbNameTxt.Text;
logOnInfo.ConnectionInfo.UserID = userNameTxt.Text;
logOnInfo.ConnectionInfo.Password = passwordTxt.Text;
Report.Database.Tables [i].ApplyLogOnInfo (logOnInfo);
}
Note that password-protected PC databases such as Microsoft Access and Paradox also use this method, but LogOnInfo.ServerName and LogOnInfo.DatabaseName should be left empty.
So I tried it like this and got an error message: TableLogOnInfo and Report were not found.
Later I discovered that TableLogOnInfo is a member of the CrystalDecisions.Shared namespace. So I added a quote:
using CrystalDecisions.Shared;
This time the problem occurred in Report.
Report? What is this? I checked all the help, but there is no such function or class!
[Seriously! This problem has troubled me for a long time! I have been searching for what the Report is! The waterscape report company is also really helpful and does not write in detail! It’s time to fight! ! ! ]
In the end, I finally discovered that Report is just a user-defined object, not an object of the system itself.
When I was confused, I suddenly thought, why not take a look at the DataBase behind the Report, what is it? Finally the problem was solved, I found the following information in the help
ReportDocument oRpt = new ReportDocument();
Report is a member of the DocumentCrystalDecisions.CrystalReports.Engine class.
Modify the code: and add a reference
using CrystalDecisions.Shared;//Responsible for interpreting the TableLogOnInfo class
using CrystalDecisions.CrystalReports .Engine;//Responsible for interpreting the ReportDocument class private void Page_Load(object sender, System.EventArgs e)
{
TableLogOnInfo logOnInfo = new TableLogOnInfo ();
// Here we must declare a reportdocument object in advance. At the same time, the data report is loaded
Reportdocument orpt = New Reportdocument ();
ORPT.LOAD ("C: \ Inetpub \ wwwroot \ exer \ pagelet \ crystal \ cr1.rpt"); // Modify to your correct position
// Create security information
// PC databases such as Microsoft Access and PARADOX, which are protected by passwords, also use this method, but logoninfo.servername
logoninfo.connectionInfo.servername = "www";
logoninfo.connectionInfo.databasename = "Archives";
logoninfo.connectionInfo.userid = "SA";
logoninfo.connectionInfo.password = "123456";
orpt.dataBase .tables [0] .applyLogoninfo (logoninfo);
// Create the connection between the .RPT file and the CrystalReportViewer file.
CrystalreportViewer1.Reportsource = ORPT;
}
The report file finally appears!
Wow, I'm so happy, I can't help but stand up and stretch my laziness!
Step 4: The code on the final full version of the code does not have systematic expansion and flexibility. There are two disadvantages:
(1) Data newspaper format files are absolute paths
(2) Once the database access right is set, it cannot be modified in the final release, especially the customer's SQL Server server cannot be based on this consideration as your debugging program environment. Introduce two better things:
(1), Server.MAPPATH function
(2) Read web.config (This example tells you how to operate the web.config configuration file)
The final modification is as follows: (complete code) The database is SQL Server2000
USing CrystalDecisions.shared; // Responsible for explaining the TableLogoninfo class
USING CRYSTALDECISIONS.CRYSTALREPORTS.ENGINE; // Responsible for explaining the ReportDocument class
Private Void Page_Load (Object SENDER, System.eventargs E)
{
TableLogoninfo logoninfo = new tableLogoninfo ();
// Here we must declare a reportdocument object in advance. At the same time, the data report is loaded
Reportdocument orpt = New Reportdocument ();
// Get the real path of the .RPT file
string path1, path2;
PATH1 = Server.mappath (" \ Exer \ pagelet ");
Path2 = PATH1+" \ Crystal \ CR1.RPT ";
//Oorpt.load 18WWWWWWWWWWWROT pagelet crystal case ");
ORPT.load (PATH2);
// Get logonininfo parameter information from web.config
string a, b, c, d;
// Get serverName
a = system.configuration .configurationSettings .appsettings ["ServerName"];
// Get DataBasename
b = system.configuration .configurationSettings .appsettings ["database"];
// Get userid
c = System.configuration .configurationSettings .appsettings ["userid"];
// Get Password
d = System.configuration .configurationSettings .appsettings ["pass"];
// Set the logoninfo parameter
logoninfo.connectionInfo.servername = a;
Logoninfo.connectionInfo.databasename = b;
logoninfo.connectionInfo.userid = C;
logoninfo.connectionInfo.password = d;
orpt.dataBase .tables [0] .applyLogoninfo (logoninfo);
// Create the connection between the .RPT file and the crystalReportViewer file.
CrystalreportViewer1.Reportsource = ORPT;
}
Explanation of the operation process of the entire demonstration:
1. In the solution resource manager, you need to store the report file, add new items: CrystalReport report, name CR1.RPT
2. When selecting the data source in the subsequent "Report Expert", be sure to choose OLE DB, and then select the driving engine of the response according to your database requirements:
SQL Server: Microsoft Ole DB PROVIDER for SQL Server
Access: Microsoft Jet.4.0
3. Enter the correct database connection. In this step, everyone will not make an error!
4. Establish a data report and save the CR1.RPT file
5. Open webform1.aspx. Add CrystalReportViewer control: Name is: CrystalreportViewer1
6. Add the above code in the page_load event in webform1.aspx.cs: the above code:
(Note: Don't forget to quote!)
*************************************************** ***
Below is the details related to this content in web.config
<appSettings>
<add key = "servername" value = "www"/>
<add key = "database" value = "Archives"/>
<add key = "userid" value = "admin"/>
<add key = "pass" value = "123456"/>
</appSettings>
*** Note that the <add key = "pass" value = "123456"/> is pass here, so he must
// Get Password
d = System.configuration .configurationSettings .appsettings ["PASS"]; here the "pass" in AppSettings ["PASS"] remains the same. Of course the name can be randomly, but it must be consistent
http://www.cnblogs.com/zhangyd1080/archive/2006/11/15/561770.html