Go to report generation using reportviewer and C #

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 it in C #CodeIt doesn't matter if you understand Ms reporting services. Of course, writing similar reports before 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.

[SPAN] place the report viewer control on form1 as follows:
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 as follows:

Value = "product list"
Color = purple

The date textbox is changed:

Value = "run data:" & today
Color = purple

[SPAN] 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 VB.. 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 ).
Table, matrix, and list are the three most commonly used controls in the table area. 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 talbe is the same as that in Textbox, that is, 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.

Only the footer area is left. before writing some C # code, you must complete the report footer. Just like adding a report header, in the open report designer, right-click and select the 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 rest is the expression generator. Expression generator is a very powerful tool in reporting services. As seen in 11, stock value is calculated using the sum function. All data in dateset can be calculated 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:

Using system. Data. sqlclient;
Using Microsoft. Reporting. winforms;

Private void form1_load (Object sender, eventargs E)
{
// Declare the connection string
String cnstring = @ "(local); initial catalog = northwind;" + "User ID = northwind; Password = northwind ";

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

// Declare the connection, command object, and other related objects
Sqlconnection conreport = new sqlconnection (cnstring );
Sqlcommand cmdreport = new sqlcommand ();
Sqldatareader drreport;
Dataset dsreport = new dsproduct ();

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

// Prepare a 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 the command object
Drreport = cmdreport. executereader ();

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

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

// Close reading and Connection
Drreport. Close ();
Conreport. Close ();

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

// Prepare the report data source
Reportdatasource RDS = new reportdatasource ();
RDS. Name = "dsproduct_dtproductlist ";
RDS. value = dsreport. Tables [0];
Rpvabrakadabra. localreport. CES. Add (RDS );

// Load the report Viewer
Rpvabrakadabra. refreshreport ();
}
Catch (exception ex)
{
// Display the 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 ".

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/mountplorer/archive/2009/05/07/4157216.aspx

Related Article

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.