Click here to Skip to main content
15,887,379 members
Articles / Web Development / ASP.NET
Article

Using the ASP.NET 2.0 ReportViewer in Local Mode

Rate me:
Please Sign up or sign in to vote.
4.79/5 (69 votes)
14 Sep 2006CPOL6 min read 2M   207   280
How to use the ASP.NET 2.0 ReportViewer control in Local mode.

Introduction

There are a good amount of materials on the net about “SQL Reporting Services in Server Mode” but it took me a while to research on using “Local Mode”, especially when parameters are involved.

The reason to use “Local Mode” instead of “Server Mode” is that in “Server Mode”, the client makes a report request to the server. The server generates the report and then sends it to the client. While it is more secure, a large report will degrade performance due to transit time from server to browser. In “Local Mode”, reports are generated at the client. No connection to the “SQL Server Reporting Services Server” is needed for local mode. Large reports will not increase wait time.

So here is an article on how to generate reports using the ASP.NET 2.0 ReportViewer web server control via Local Mode with a parameterized stored procedure. I am using ASP.NET 2.0, Visual Studio 2005, and SQL Server 2005 with Application Block. If you are not using Microsoft Application Block, just call the stored procedure via the SQL Command object without using the SQL Helper class in the example.

Using the Northwind database, our example will prompt the user for a category from a dropdown list and display all the products under the selected category.

Step 1: Create a parameterized stored procedure

SQL
ALTER PROCEDURE  ShowProductByCategory(@CategoryName nvarchar(15) )
AS
SELECT  Categories.CategoryName, Products.ProductName, 
        Products.UnitPrice, Products.UnitsInStock
FROM    Categories INNER JOIN Products ON 
        Categories.CategoryID = Products.CategoryID
WHERE   CategoryName=@CategoryName
RETURN

Step 2: Create a DataTable in a typed DataSet using the DataSet Designer

Under Solution Explorer, right-click on the App_Code folder. Select “Add New Item”. Select “DataSet”. Name your dataset, e.g., DataSetProducts.xsd, and click Add. The TableAdapter Configuration Wizard should appear automatically, if not, right click anywhere on the DataSet Designer screen and select “Add” from the context menu. Select the “TableAdapter” to bring up the wizard. Follow the wizard to create your data table. I chose “Use existing stored procedures” as the command type and specified “ShowProductByCategory” as the Select command. I also highlighted “CategoryName” as the Select procedure parameter.

The results from the stored procedure created in step 1 will eventually be placed into this data table created in step 2 (Fig. 1). Report data is provided through a data table.

Image 1

Fig. 1 DataSetProducts.xsd contains a DataTable to be used as a report data source.

Step 3: Create a report definition

Under Solution Explorer, right-click and select “Add New Item”. Select the “Report” template. I will use the default name Report.rdlc in this example. Click “Add” to add Report.rdlc to your project. “rdl” stands for Report Definition Language. The “c” stands for Client. Hence, the extension .rdl represents a server report. The extension .rdlc represents a local report.

Drag a “Table” from the Toolbox onto the report designer screen (Fig.2). The Toolbox display here is specific to the report template. It shows controls to be used in a report as opposed to controls to be used in a web form. The “Table” has three bands, the header, detail, and the footer bands.

A “Table” is a data region. A data region is used to display data-bound report items from underlying datasets. Although a report can have multiple data regions, each data region can display data from only one DataSet. Therefore, use a stored procedure to link multiple tables into a single DataSet to feed the report.

Image 2

Fig. 2 Toolbox contains controls specific to the report template.

Open up the “Website Data Sources” window (Fig.3). Locate the “DataSetProductsDataSet (created in Step 2). Expand to see the columns in the DataTableShowProductByCategory”. The table is named “ShowProductByCategory” because we chose “Use existing stored procedure” in the TableAdapter Configuration Wizard. And our procedure name is “ShowProductByCategory”.

Drag the column “ProductName” from the “Website Data Sources” window, and drop it in the Detail row (middle row). Drag “UnitPrice” into the middle row-second column and “UnitsInStock” into the last column. The header is automatically displayed. You can right click on any field in the detail row (e.g., right click on “Unit Price”) and bring up the context menu. Select Properties from the context menu. Select Format tab to format the “Unit Price” and “Units In Stock” accordingly.

Image 3

Fig 3. Website Data Sources window shows typed datasets in your app and its columns.

Step 4: Drag a ReportViewer web server control onto an .aspx form

Drag a DropDownList control onto a new web form (Fig. 4). Use the “Choose Data Source” option from the “DropDownList Task” to bind the CategoryName field from the Category table. Remember to enable autopostback. Users can then make their selection as an input to the stored procedure. While I am using a DropDownList in this example, you can use textboxes and other controls to prompt users for additional input.

Drag a ReportViewer web server control onto the web form. Set its Visible property to false. Also notice, the ReportViewer web server control in ASP.NET 2.0 provides exporting capability. You can select between Excel format or PDF format. However, I find that what you see on screen is not always what you get from the printer. You will have to experiment with the output format further.

Image 4

Fig. 4 Set this web page as the StartUp page.

Next, bring up the smart tag of the ReportViewer control (Fig. 5). Select “Report.rdlc” in the “Choose Report” dropdown list. “Report.rdlc” was created in Step 3. Local Reports have the extension .rdlc. Server Reports are labeled with .rdc.

Image 5

Fig. 5 Associate the report definition file (.rdlc) to the ReportViewer control

Step 5: Write source code for the “Run Report” button to generate the report based on user selections

Don’t forget to include the “Microsoft.Reporting.WebForms” namespace in your code-behind file.

C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.ApplicationBlocks.Data;
using Microsoft.Reporting.WebForms;

public partial class ReportViewerLocalMode : System.Web.UI.Page
{
    public string thisConnectionString = 
       ConfigurationManager.ConnectionStrings[
       "NorthwindConnectionString"].ConnectionString;

    /*I used the following statement to show if you have multiple 
      input parameters, declare the parameter with the number 
      of parameters in your application, ex. New SqlParameter[4]; */

    public SqlParameter[] SearchValue = new SqlParameter[1];

    protected void RunReportButton_Click(object sender, EventArgs e)
    {
        //ReportViewer1.Visible is set to false in design mode
        ReportViewer1.Visible = true;
        SqlConnection thisConnection = new SqlConnection(thisConnectionString);
        System.Data.DataSet thisDataSet = new System.Data.DataSet();       
        SearchValue[0] = new SqlParameter("@CategoryName", 
                         DropDownList1.SelectedValue);

        /* Put the stored procedure result into a dataset */
        thisDataSet = SqlHelper.ExecuteDataset(thisConnection, 
                      "ShowProductByCategory", SearchValue);

        /*or   thisDataSet = SqlHelper.ExecuteDataset(thisConnection, 
               "ShowProductByCategory", dropdownlist1.selectedvalue); 
               if you only have 1 input parameter  */

        /* Associate thisDataSet  (now loaded with the stored 
           procedure result) with the  ReportViewer datasource */
        ReportDataSource datasource = new 
          ReportDataSource("DataSetProducts_ShowProductByCategory", 
          thisDataSet.Tables[0]);

        ReportViewer1.LocalReport.DataSources.Clear();
        ReportViewer1.LocalReport.DataSources.Add(datasource);
        if (thisDataSet.Tables[0].Rows.Count == 0)
        {
            lblMessage.Text = "Sorry, no products under this category!";
        }

        ReportViewer1.LocalReport.Refresh();
    }
}

Step 6: Build and Run the Report

Press F5 to run the .aspx. Click on the “Run Report” button to see the list of products based on the selected category from the dropdown list (Fig. 6).

Image 6

Fig. 6 Click on the “Run Report” button to generate a local report

Be sure to add reference of the ReportViewer to your web app, and note that your ReportViewer web server control has registered an HTTP handler in the web.config file. Your web.config file should have the following string:

XML
<httpHandlers>
    <add path="Reserved.ReportViewerWebControl.axd" verb="*" 
         type="Microsoft.Reporting.WebForms.HttpHandler, 
               Microsoft.ReportViewer.WebForms, 
               Version=8.0.0.0, Culture=neutral, 
               PublicKeyToken=?????????????"
         validate="false" />
</httpHandlers>

When you use the Visual Studio 2005 ReportViewer web server control in your website, you will need to copy the "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\ReportViewer\ReportViewer.exe" to your server and run it before you post those web pages with the ReportViewer control.

Well, there you have it. This is a simple example of creating a report in local mode. I hope you find the example useful. Happy computing!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralDataSet not show field Pin
Umesh Jha13-May-09 23:59
Umesh Jha13-May-09 23:59 
GeneralRe: DataSet not show field Pin
ShirleySW14-May-09 3:23
ShirleySW14-May-09 3:23 
QuestionWhat if I am not using Store Procedures? Pin
Alejandro20097-May-09 12:28
Alejandro20097-May-09 12:28 
AnswerRe: What if I am not using Store Procedures? Pin
ShirleySW8-May-09 4:19
ShirleySW8-May-09 4:19 
GeneralRe: What if I am not using Store Procedures? Pin
Alejandro20098-May-09 6:26
Alejandro20098-May-09 6:26 
QuestionRe Report viewer tutorial Pin
Bubbles21-Apr-09 9:25
Bubbles21-Apr-09 9:25 
AnswerRe: Re Report viewer tutorial Pin
ShirleySW1-Apr-09 13:01
ShirleySW1-Apr-09 13:01 
AnswerA bit puzzled Pin
Bubbles22-Apr-09 3:28
Bubbles22-Apr-09 3:28 
Hi Shirley

Thanks for your prompt reply , I had trouble reading it , I seem only to be able to view comments once I have posted a message hence the dummy message weird ???

I am using VS2008 , I simply take the publish web site option

The result is I have a bin folder, a Default.ASPX and a web config file in my deployment folder.

The bin folder contains only Testreportviewer.dll (Project name) and Testreportviewer.

There is no sign of the rdlc I thought this was compiled into my Testreportviewer.dll.

I have also included the report viewer dll's in the bin .



I am not sure I understand your reply (sorry) do i need to create a \Reports$SQL2008 in my path and copy my rdlc into this folder manually , the publish option does not include it.

What is an rdlc , is it not an object that gets compiled into my dll?


Should my structure on the server be

myapp
bin
testreportviewer.dll


default.aspx

Reports$SQL2008
report1.rdlc

web.config


What do I need to put in my web.config file I corrently have

<add assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
				<add assembly="Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>




and
<br />
<br />
			<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>



What do I need to put in my web config file to point to my rdlc , Can you send me a sample of yours ? I include a complete listing of my web.config at the end of my message.


My access to the server is very limited , I am using a cheap but very obliging asp hosting provider.

The reporting feature seems to be excellent but frustrating if I can only run it on local host.

Thanks for you article and your reply I hope yoy can help me get this feature deployed.
Good Luck. Hope this help.


Donncha


<?xml version="1.0"?><br />
<configuration><br />
	<configSections><br />
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"><br />
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"><br />
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/><br />
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"><br />
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/><br />
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/><br />
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/><br />
					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/><br />
				</sectionGroup><br />
			</sectionGroup><br />
		</sectionGroup><br />
	</configSections><br />
	<appSettings/><br />
	<connectionStrings><br />
		<add name="matrixpservConnectionString" connectionString="Data Source=mssql2005express.webhost.ie\helm;Initial Catalog=matrixpserv;Persist Security Info=True;User ID=pserv;Password=pserv//" providerName="System.Data.SqlClient"/><br />
	</connectionStrings><br />
	<system.web><br />
		<!-- <br />
            Set compilation debug="true" to insert debugging <br />
            symbols into the compiled page. Because this <br />
            affects performance, set this value to true only <br />
            during development.<br />
        --><br />
		<compilation debug="true"><br />
			<assemblies><br />
				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/><br />
				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/><br />
				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/><br />
				<add assembly="Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/><br />
				<add assembly="Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/><br />
			</assemblies><br />
			<buildProviders><br />
				<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/><br />
			</buildProviders><br />
		</compilation><br />
    <br />
		<!--<br />
            The <authentication> section enables configuration <br />
            of the security authentication mode used by <br />
            ASP.NET to identify an incoming user. <br />
        --><br />
		<authentication mode="Windows"/><br />
		<!--<br />
            The <customErrors> section enables configuration <br />
            of what to do if/when an unhandled error occurs <br />
            during the execution of a request. Specifically, <br />
            it enables developers to configure html error pages <br />
            to be displayed in place of a error stack trace.<br />
<br />
        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"><br />
            <error statusCode="403" redirect="NoAccess.htm" /><br />
            <error statusCode="404" redirect="FileNotFound.htm" /><br />
        </customErrors><br />
        --><br />
    <customErrors mode="Off"/><br />
<br />
    <pages><br />
			<controls><br />
				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
				<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
			</controls><br />
		</pages><br />
		<httpHandlers><br />
			<remove path="*.asmx" verb="*"/><br />
			<add path="*.asmx" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/><br />
			<add path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/><br />
			<add path="ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/><br />
			<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="false"/><br />
		</httpHandlers><br />
		<httpModules><br />
			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
		</httpModules><br />
	</system.web><br />
	<system.codedom><br />
		<compilers><br />
			<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"><br />
				<providerOption name="CompilerVersion" value="v3.5"/><br />
				<providerOption name="WarnAsError" value="false"/><br />
			</compiler><br />
		</compilers><br />
	</system.codedom><br />
	<!-- <br />
        The system.webServer section is required for running ASP.NET AJAX under Internet<br />
        Information Services 7.0.  It is not necessary for previous version of IIS.<br />
    --><br />
	<system.webServer><br />
		<validation validateIntegratedModeConfiguration="false"/><br />
		<modules><br />
			<remove name="ScriptModule"/><br />
			<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
		</modules><br />
		<handlers><br />
			<remove name="WebServiceHandlerFactory-Integrated"/><br />
			<remove name="ScriptHandlerFactory"/><br />
			<remove name="ScriptHandlerFactoryAppServices"/><br />
			<remove name="ScriptResource"/><br />
			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
			<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/><br />
		</handlers><br />
	</system.webServer><br />
	<runtime><br />
		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><br />
			<dependentAssembly><br />
				<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/><br />
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/><br />
			</dependentAssembly><br />
			<dependentAssembly><br />
				<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/><br />
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/><br />
			</dependentAssembly><br />
		</assemblyBinding><br />
	</runtime><br />
</configuration>





GeneralRe: A bit puzzled Pin
rexahs4-Jun-09 11:04
rexahs4-Jun-09 11:04 
QuestionCan I use Group in ReportViewer Pin
Intellect25-Mar-09 20:56
Intellect25-Mar-09 20:56 
Questionhow can I use two parameters Pin
Member 43322616-Mar-09 22:10
Member 43322616-Mar-09 22:10 
AnswerRe: how can I use two parameters Pin
ShirleySW9-Mar-09 3:39
ShirleySW9-Mar-09 3:39 
GeneralRe: how can I use two parameters Pin
Member 433226110-Mar-09 2:48
Member 433226110-Mar-09 2:48 
GeneralRe: how can I use two parameters Pin
ShirleySW10-Mar-09 3:14
ShirleySW10-Mar-09 3:14 
GeneralRe: how can I use two parameters Pin
Member 433226111-Mar-09 3:51
Member 433226111-Mar-09 3:51 
GeneralRe: how can I use two parameters Pin
ShirleySW11-Mar-09 4:00
ShirleySW11-Mar-09 4:00 
GeneralRe: how can I use two parameters Pin
Member 433226112-Mar-09 21:26
Member 433226112-Mar-09 21:26 
Generalproblem with ReportDataSource [modified] Pin
Member 43322616-Mar-09 21:12
Member 43322616-Mar-09 21:12 
GeneralRemote Server Pin
salimsaifi19-Nov-08 0:52
salimsaifi19-Nov-08 0:52 
GeneralRe: Remote Server Pin
ShirleySW19-Nov-08 3:10
ShirleySW19-Nov-08 3:10 
Questionhow to run the .exe file on server Pin
santosh jha"Don"15-Nov-08 1:35
santosh jha"Don"15-Nov-08 1:35 
AnswerRe: how to run the .exe file on server Pin
ShirleySW17-Nov-08 3:34
ShirleySW17-Nov-08 3:34 
GeneralProblem with using parameters in ReportViewer Pin
vgandhi2-Nov-08 23:50
vgandhi2-Nov-08 23:50 
GeneralRe: Problem with using parameters in ReportViewer Pin
ShirleySW3-Nov-08 4:47
ShirleySW3-Nov-08 4:47 
GeneralRe: Problem with using parameters in ReportViewer Pin
vgandhi3-Nov-08 4:52
vgandhi3-Nov-08 4:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.