(SHARE) Use reportviewer and C # to generate a report step by step

Source: Internet
Author: User

People in the workplace will feel a bit of emotion when writing reports. A neat and beautiful report will add a lot of color in front of your boss, or even raise your salary-Everyone prefers to raise your salary, right? This article describes how to use MS Reporting Services 2005 to create a report and use a C # applet to generate it.
This article assumes that the reader has a preliminary understanding of Visual Studio 2005 IDE and can write code in C #. Understanding Ms reporting services does not matter. Of course, similar reports have been written before, which will help you get started faster. Now, roll up your sleeves and get started!
See Figure 1. How complicated is this report? Guess how long it will take to complete? In terms of complexity, it is just a simple report extracted from northwind-> Products (SQL Server 2000). In terms of time, I believe it won't take you an entire hour.

Figure 1

Next, we start to create a report. First, we need to compile a C # smallProgram.
Step 1: Create a Windows Application

Select the File menu, create-project, select C # From the project type, and select a Windows application from the right-side dialog box. In the Name Bar, it is best to use a name indicating the purpose of the program; in the location column, specify the directory you want to save. After that, there will be a form1 in the project. Let's start with its Form Designer.
Modify the attributes of form1 as follows. Of course, you can also modify other attributes based on your preferences:
Form1.text = "Ms Reporting Services 101 with Smart Client"

Form1.size = 750,300
Step 2: Add a report viewer to a form)

What is a report viewer? Just like a DVD player is required to watch a DVD, we need a report viewer to preview the report. For the person who writes the report, the report viewer gives the report life. It can not only preview the output, but also help generate the report information in various formats (PDF or Excel ), print it out.
Follow these steps to place the report viewer control on form1:

Find the toolbox-data-Report viewer and drag it to form1. This creates a new instance named reportviewer1. By setting reportviewer1.dock = fill, the report viewer fills the entire area of the form to display the report. After completing steps 1 and 2, the project looks like 2:

Figure 2

Step 3: Add a dataset to the Project)

A dataset comes with the report viewer. It stores and provides raw data from the data source, so that we can process the raw data or output it in the C # program.
Follow these steps to add a dataset:

Select Add-new project-dataset from solution resource browser, change its name dataset1 to dsproduct, and click Add.
Add a data table to the newly created dataset. A data table is actually used to load report data. When designing a report, it uses the relevant information in dataset/datatable.
Add the data table to the dataset (dsproduct) as follows:

Double-click dsproduct from the solution resource browser. The design view is displayed, right-click, and choose add-data table. Then, click the table header to change the name to dtproductlist, 3:

Figure 3

Next, add a column for the data table (dtproductlist). The design view should be 4. Right-click dtproductlist and choose add -- column ).

Figure 4

Repeat the preceding steps to add the following columns:
Productname (string)

Quantityperunit (string)

Unitprice (double)

Unitsinstock (double)

Unitvalue (double): A calculation Domain Based on unitsinstock * unitprice
When adding a column, the default value is the string data type. After adding the column, go to the Properties window and modify the corresponding column as the double type. See Figure 5. The current data table looks like this. You can also view the Properties window to modify the data type.

Figure 5

Step 4: Add a report for the project

So far, we have created a project and added a report viewer and Dataset. Now, it is time to create a neat and beautiful report.
To generate a report (rptproductlist. rdlc), follow these steps ):

Select Add-New Project-Report from solution resource browser, change report1.rdlc to rptproductlist. rdlc, and click Add. The project may look like Figure 6. After adding a report, you can start designing with a dataset.

Figure 6

Whether you are a beginner in designing reports for the first time, or experienced in the field, you must deal with the following three basic report areas: Header (or header), footer, and table body. In general, when designing a report, there should be a draft, such as the size of the paper, the layout, and so on. It is usually the size of the letter paper and the vertical layout. Of course, it would be better to draw a sketch on the paper before you can do it. Let's look back at 1. In the header, there is a report name and report date, and the table body contains a list of product-related information, while the footer contains the page number.
Let's start with the header. When a new report is added to a project, only the table body can be seen in the report designer by default. Right-click outside the table body of the report designer and select a header. This will add a header to the report. You can adjust the height of the header and table area as needed. See figure 7, figure 7 reduces the table height and increases the header height.

Figure 7

In the toolbox of the report designer, you can see various controls used to design reports. In this example, Textbox, line, and table controls are used. Now let's start designing the header. Drag two textbox boxes and place them in the header area. textbox displays both static and dynamic data, while the line control separates the headers from the table area. After the control is placed, you can modify its properties to display the values we need. For example, you can specify a textbox as the report title, while another textbox displays the current date. After selecting Textbox, you can directly enter static text in it.
Modify the title textbox property value as follows:
Value: product list color value: Purple
The date textbox property value is changed:
Value = "run data:" & today color value: Purple
Note that the value attribute of the date textbox starts with the "=" symbol, which means that it is not a simple static text, but an expression. This expression is the string "run date" and.. Net script. In addition, you can specify any name you want for all objects in the Report. Generally, you can keep the default name for most controls, in this example, the name (name attribute) of the title textbox is specified as "txttitle ".
Refer to Figure 8. After the header is designed, it should look like this:

Figure 8

It is the table body. The table body is the detailed area of the bearer information and the most important part of the entire report. You can also see that when you add a report to a project, the table body has been automatically added, we only need to put some controls on it.
Traditionally, the table body area is used to display detailed data (in this example, it is the product information) and usually contains multiple rows of information, the table area will also expand, but in general, the report will only be designed as one page (letter or A4 size ). In the table body area, there are three most commonly used controls: Table, matrix, and list. In this example, the table control is used. On the report design page, drag and place the table control in the table area. You will see that this will generate a table with three rows and three columns, the middle column is marked as header, detail, and footer.
When you know that the table control is just a combination of a bunch of Textbox, isn't it a little surprised. By the way, each cell in a table is the same as that in textbox. That is to say, you can enter static text or specify a dynamic expression. Before designing the table partition, remember to add two more columns (five columns in our report). It is very easy to add columns. follow these steps:
1. Select the table control in the table body area.

2. left-click the header of the rightmost column (assuming that you add a new column from the right ).

3. Right-click the header and select "insert column to the right" (insert column on the right ).
Now the report looks like Figure 9. You can adjust the column width based on the data in the column.

Figure 9

Most of you have used Excel or similar items. You can regard the table control as a mini worksheet, where you can select the border type, change the font of any cell, and so on. Therefore, what needs to be done is to design tables in the format previously imagined. We start from the first column, and then each column is the same. Click the cell at the top of the column and enter the following in sequence:
Header 1: "Product Name" header 2: "packaging" header 3: "unit price" header 4: "units in stock" header 5: "stock value"
In the subsequent detailed data area (that is, the previous detail), you need to input an expression, which is dsproduct. in dtproductinfo, You can manually enter an expression or drag and drop the column from the data source toolbox (see figure 7 on the left. If you want to manually enter the data, from the first column to the last column in the data area, click the cell and enter:
Detail 1: "= Fields! Productname. Value"

Detail 2: "= Fields! Quantityperunit. Value"

Detail 3: "= Fields! Unitsinstock. Value"

Detail 4: "= Fields! Unitprice. Value"

Detail 5: "= Fields! Unitsinstock. Value * fields! Unitprice. Value"
Pay Attention to detail 5, which is an output after multiplying units in stock and unit value. In addition, if you drag a column to the data area of the table control, if the header is empty, it will automatically add the header. Finally, add a accumulative column to the footer of the table control, select the footer cell of the 4th and 5th columns in the table area, and enter:
Cell 4: "total value :"

Cell 5: "= sum (Fields! Unitsinstock. Value * fields! Unitprice. Value )"
Click cell 5. A built-in sum () function is used to obtain the accumulative result.
At last, only the footer area is left. At the beginning, write some C #CodeYou also need to complete the report footer. Just like adding a report header, right-click the report designer and select the footer (page footer), as shown in figure 7. Drag a line and Textbox Control to the footer area and enter the following expression in the textbox:
Value: = "Page:" & globals! Pagenumber & "/" & globals! Totalpages
We can see that pagenumber and totalpages are used here, both of which are global variables.
Now, the report should be like Figure 10. Here, the color is changed, the right alignment of the numeric data is adjusted, and the table is regarded as an Excel worksheet. You can adjust the appearance you want at will.

Figure 10

It's almost done!

The following describes the expression generator: The expression generator is a very powerful tool in reporting services. As seen in 11, the stock value is calculated using the sum function, all data in dateset can be created by "fields!" Keyword access.

Figure 11

Step 5: Write C # code that gives the report life

In the solution resource browser, right-click form1 and choose view code from the shortcut menu to add the following code to form1_load:

View code

 Private   Void Form1_load ( Object Sender, eventargs E)
{
// Declare connection string
String Cnstring = @" (Local); initial catalog = northwind; " +" User ID = northwind; Password = northwind " ;

// If you use the standard security attribute, change it to the following code:
// String cnstring = @ "Data Source = (local); initial catalog = northwind; Integrated Security = sspi ";

// Declare connections, command objects, and other related objects
Sqlconnection conreport = New Sqlconnection (cnstring );
Sqlcommand cmdreport =New Sqlcommand ();
Sqldatareader drreport;
Dataset dsreport = New Dsproduct ();

Try
{
// Open connection
Conreport. open ();

// Prepare the connection object to put the obtained data into the dataset.

Cmdreport. commandtype = commandtype. text;
Cmdreport. Connection = conreport;
Cmdreport. commandtext = " Select top 5 * from products order by productname " ;

// Read data from command objects
Drreport = cmdreport. executereader ();

// With ADO. net, read data can be directly loaded into a data set.

Dsreport. Tables [ 0 ]. Load (drreport );

// Disable read and Connection
Drreport. Close ();
Conreport. Close ();

// Provide local report data for the viewer
Reportviewer1.localreport. reportembeddedresource = " Windowsapplication1.rptproductlist. rdlc " ;

Reportviewer1.localreport. CES. Clear ();

// Prepare a report data source
Reportdatasource RDS = New Reportdatasource ();
RDS. Name = " Dsproduct_dtproductlist " ;
RDS. value = dsreport. Tables [ 0 ];
Reportviewer1.localreport. CES. Add (RDS );

// Load report Viewer
Reportviewer1.refreshreport ();
}
Catch (Exception ex)
{
// Show error message
MessageBox. Show (ex. Message );
}
Finally
{
// Check whether the connection is still open. If yes, close it.
If (Conreport. State = connectionstate. open)
{
Conreport. Close ();
}
}
}

As you can see, you may wonder why "Top 5" is used in the SELECT query statement, which is only for demonstration purposes and limits the output, get the cumulative result from 1. In addition, the name attribute of reportdatasource should always be "dataset_datatable ".

Csdn http://blog.csdn.net/mountplorer/article/details/4157216

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.