Crystal Reports for Visual Studio 2005 in CSharp

This article, written by MSDN Virtual Labs, guides you through the creation of a Crystal Reports web application that reports off of data from an Object Collection. You will create a unique class to hold stock market values, instantiate the class, and more.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 104
February 02, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Objectives

After completing this lab, you will be better able to:

  • Create a unique class to hold stock market values.
  • Instantiate the class.
  • Populate and object collection with data.
  • Dynamically add data through a web form.
  • Create a crystal report with the Crystal Report Designer.

Scenario

This lab guides you through the creation of a Crystal Reports web application that reports off of data from an Object Collection. The application is developed with Crystal Reports for Visual Studio 2005 Beta 2.

Then you will create a unique class to hold stock market values, instantiates the class and populates an object collection with data, and dynamically adds further data through a web form. You will then create a Crystal report with the Crystal Report Designer control that connects to the object collection and dynamically generates a chart and stock summary

Estimated Time to Complete This Lab

60 Minutes

Exercise 1: Web Application Setup

Scenario

In this exercise, you will create a new Web Site and apply the standard settings needed to complete the lab.

 Tasks              Detailed Steps

  1. Create the Web site in this section you will create a new ASP.NET Web Site in Visual Studio.

    1. Double-click the  Visual Studio 2005 Beta 2 shortcut on the desktop.

    2. Click File | New | Web Site.

    3. In the New Web Site dialog box, click ASP.NET Web Site.

    4. In the Location list, select File System.

    5. In the Language list, select Visual C#

    6. In the Location text field, accept the default path and name.

    7. Click OK.

  2. Adding the Crystal Report Viewer Control.

    1. From the Solution Explorer, double click Default.aspx to open the web form.

    2. Click the Design button at the bottom of the form to change the Web Form to Design view.

    3. From the Toolbox, expand the Crystal Reports node and locate the CrystalReportViewer control.

    4. Drag the CrystalReportViewer control onto the Web Form.

    5. If the Smart Task panel CrystalReportViewer Tasks is open, press Esc on your keyboard to close it.

      The Smart Task panel is a new feature to Visual Studio 2005 that allows for a reduced code approach to creating projects. In this lab, you will use a programmatic approach, and thus will not use the Smart Task panel. 

    6. Click the Properties tab and select the CrystalReportViewer

    7. From the Properties window, set the ID property to crystalReportViewer

    8. From the File menu, click SaveAll.

  3. Adding the Programmatic Settings.

    1. Click the Solution Explorer tab. 

    2. In the Solution Explorer, right click Default.aspx and click View Code.

    3. Above the class signature, add a "using" declaration for the namespaces of the assemblies that are listed below.

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

    4. Within the class, add a new private scope helper method, with no return value, named ConfigureCrystalReports().

      private void ConfigureCrystalReports()
      {
      }


      ConfigureCrystalReports() is a helper method that interacts with the report at runtime. It also controls programmatic interaction with the report. In order to correctly configure the CrystalReportViewer, it must be called from Page_Init().

    5. Add the Page_Init event handler. Use the exact syntax shown.

      private void Page_Init(object sender, EventArgs e)
      {
      }


      In a C# Web form in Visual Studio 2005, the Page_Init event handler in the code-behind class is automatically wired to the Init event. The event handler signature must match exactly in order to be called.

    6. Finally, within the Page_Init event handler, enter a call to the ConfigureCrystalReports() helper method.

      ConfigureCrystalReports();

    7. From the File menu, click Save All.

      You are now ready to create your custom stock market information class.

Take Microsoft software for a test drive. With MSDN Virtual Labs, you get full access to all available Microsoft products through 90-minute modules, each with its own downloadable manual. Try this lab out now.

Exercise 2: Creating a Custom Stock Market Information

Scenario

In this exercise, you will create a custom class to hold stock market information. This class will be used to populate an Object Collection.

        Tasks            Detailed Steps

  1. Adding a class to your Website.

    1. In Solution Explorer, right-click the web site name that is in bold type and then click Add New Item.

      The Add New Item dialog box appears.
    2. In the Visual Studio Installed Templates field, select Class 
    3. In the Name field, type Stock, and then click Add.
    4. In the dialog box that appears, click Yes.

      In Visual Studio 2005, all classes must be placed inside of an App Code folder if they are to be generally consumable. When you click the Add button, an alert box will ask you if you would like to place your class inside of this App_Code folder.

    5. The Stock class must be set to public scope to be accessed when you create the report. Verify that the class you have created is public. If not, add the public modifier to the class signature to expose the class to the embedded Crystal Report Designer.

      public class Stock
      {
         public Stock()
         {
         }
      }

    6. Within the class, add three private fields.

      private string _symbol;
      private double _price;
      private int _volume;

      Next, you will add three public read/write properties to encapsulate the three private fields. 
    7. Create a new property named Symbol.

      public string Symbol
      {
          get
          {
                return _symbol;
          }
          set
         {
                _symbol = value;
         }
      }

    8. Create a new property named Price.

      public double Price
      {
        get
        {
           return _price;
        }
        set
        {
           _price = value;
        }
      }

    9. Create a new property named Volume.

      public int Volume
      {
        get
        {
             return _volume;
        }
        set
        {
             _volume = value;
        }
      }


    10. Finally, create a new constructor that takes the three public properties as arguments.

      public Stock (String symbol, int volume, double price)
      {
         _symbol = symbol;
         _volume = volume;
         _price = price;
      }

    11. From the Build menu, click Build Website.

      If you have any build errors, fix them now.
    12. You are now ready to access this object from the embedded Crystal Report Designer.

Exercise 3: Creating a Crystal Report

Scenario

In this exercise, you create a new Crystal report in the embedded Crystal Report Designer and then bind this report to the Stock object.

        Tasks              Detailed Steps

  1. Create a Crystal Report.

    1. Right-click the web site name and click Add New Item.
    2. In the Add New Item dialog box, select Crystal Report.
    3. In the Name field, enter StockObjects.rpt, and then click Add
    4. In the Crystal Reports Gallery dialog box, click OK.
    5. In the Standard Report Creation Wizard dialog box, expand Project Data and the sub node .NET Objects.

      A list of classes within the project appears.
    6. Expand the Stock class to view a selectable sub node.
    7. Click the right-arrow > to move the Stock class sub node to the Selected Tables panel.
    8. Click Next.
    9. Expand Stock and click the >> to move all columns to the Fields to Display panel.
    10. Click Next.
    11. Select Symbol and click the right-arrow > to move it into the Group By panel.
    12. Click Finish.

Take Microsoft software for a test drive. With MSDN Virtual Labs, you get full access to all available Microsoft products through 90-minute modules, each with its own downloadable manual. Try this lab out now.

Exercise 4: Bind your Crystal Report to the Crystal Report Viewer

Scenario

In this exercise, you will bind the Stock Objects report to the Crystal Report Viewer, set the data source of the report to an Object Collection, and populate the Object Collection programmatically.

        Tasks              Detailed Steps

  1. Binding the Report to the Crystal Report Viewer.

    1. Switch to the default Code-Behind class, Default.aspx.cs.
    2. Above the class signature, add a "using" declaration to the top of the class for the System.Collections namespace.

      using System.Collections;

      This reference gives you access to the ArrayList class. ArrayList implements ICollection. This qualifies ArrayList as one of several class types that can be used to build an object collection that is recognized by Crystal Reports.
    3. Add a new class-level ArrayList, call it stockValues.

      private ArrayList stockValues;
    4. Add a new class-level declaration for the ReportDocument report wrapper class, with the variable name stockObjectsReport. Set its access modifier to private.

      private ReportDocument StockObjectsReport;
    5. Within the ConfigureCrystalReports()method you created in Exercise 1: Web Application Setup, declare a string variable, name it reportPath, and assign to it a runtime path to the local report. Pass the name of the local report file as a string parameter into the Server.MapPath() method. This maps the local report to the file path at runtime.

      String reportPath = Server.MapPath("StockObjects.rpt");

    6. Add two line breaks, and instantiate the ReportDocument class.

      StockObjectsReport = new ReportDocument(); 
    7. On the next line, Call the Load()method of the ReportDocument instance and pass into it the reportPath string variable.

      StockObjectsReport.Load(reportPath);

      The ReportDocument class is a member of the CrystalDecisions.CrystalReports.Engine namespace. You have added a "using" [C#] declaration for this namespace in Exercise 1: Web Application Setup. When you instantiate ReportDocument and load a report, you gain access to the report through the SDK.
    8. Next, set the data source of the report to the stockValues ArrayList.

      StockObjectsReport.SetDataSource(stockValues);
    9. Finally, bind the ReportSource property of the CrystalReportViewer to the ReportDocument instance.

      crystalReportViewer.ReportSource = stockObjectsReport;

      At this point, the Stock Objects report is bound to the Crystal Report Viewer and the page displays the correct report; however, the report is currently bound to an empty data source, thus the report has no information to display. In the next step, you will programmatically populate the stockValues ArrayList with sample data.

  2. Populating the Object Collection Programmatically.

    In this task, you will add Session code to the ASPX code-behind class. If there are no values currently held in session, default values will be created. If there are values in session, they will be assigned to the stockValues ArrayList.

    1. Within the class, add a new public scope helper method, with no return value, named PopulateStockValuesArrayList().

      public void PopulateStockValuesArrayList()
      {
      }

    2. Within the PopulateStockValuesArrayList()method, before the existing code, create an if/else conditional block that checks whether a Session object named stockValues exists.

      if(Session["stockValues"] == null)
      {
      }
      else
      {
      }

    3. Within the If block, instantiate a new ArrayList().

      stockValues = new ArrayList();
    4. Next, use the overloaded constructor for the Stock class to create and instantiate three instances of Stock.

      Stock s1 = new Stock("AWRK",1200,28.47);
      Stock s2 = new Stock("CTSO",800,128.69);
      Stock s3 = new Stock("LTWR",1800,12.95);

    5. Add these three instances to stockValues.

      stockValues.Add(s1); stockValues.Add(s2); stockValues.Add(s3);
    6. Add the updated stockValues ArrayList into session.

      Session["stockValues"]=stockValues;
    7. Inside of the Else block, write a line to assign the current values held in session to the stockValues ArrayList.

      stockValues = (ArrayList)Session["stockValues"];

    8. Finally, call the PopulateStockValuesArrayList() from the ConfigureCrystalReports()method.
    9. This should be the first line of code executed in the ConfigureCrystalReports() method.

      PopulateStockValuesArrayList();

    10. From the Build menu, click Build Solution.

      If you have any build errors, fix them now.
    11. From the Debug menu, click Start Debugging.
    12. If this is the first time you have started debugging, a dialog box appears and states that the Web.config file must be modified. Click the OK button to enable debugging.

      The Default.aspx page loads into your browser with three default values.
    13. Close the Internet Explorer window.

Take Microsoft software for a test drive. With MSDN Virtual Labs, you get full access to all available Microsoft products through 90-minute modules, each with its own downloadable manual. Try this lab out now.

Exercise 5: Adding Data Dynamically to the Stock Report

Scenario

In the previous exercise, you populated the Object Collection programmatically. In this exercise, you will learn how to dynamically add information to your data source from your website. This information will automatically update in your report.

         Tasks        Detailed Steps 

  1. Adding Controls to the Web Form. 

     

    1. Open the Default.aspx file in Design View.

      To open an ASPX page in design view, first open the file, and then click the Design button at the bottom of the form.

    2. Click the CrystalReportViewer control to select it.
    3. Press the left arrow key on your keyboard so that the flashing cursor appears, and the press Enter to move the viewer down the page four times.
    4. From the Toolbox drag a TextBox control onto the web form.
    5. From the Property menu, set the ID to symbol. 
    6. Drag a second TextBox control onto the web form. Position the second TextBox below the first. 
    7. From the Property menu, set the ID to price.
    8. Drag a third TextBox control onto the web form. Position the third TextBox below the second. 
    9. From the Property menu, set the ID to volume.

      At this point, you may find it useful to add text beside each TextBox control to help identify which control corresponds to which parameter.

    10. Next, from the Toolbox, drag a Button control onto the web form. Place the button below the three TextBox controls.
    11. From the Property menu set the ID of the Button to addStockInformation.
    12. Set the Text of the Button to Add Stock Information.
    13. Finally, double click on the Add Stock Information button.
    14. Double clicking on the Button control will open up the Code-behind class and automatically generate an addStockInformation_Click() event handler.
  2. Adding Information to the Collection.
    1. Inside of the addStockInformation_Click() event handler, create and instantiate a new Stock object.

      Stock temp = new Stock();
    2. Within the addStockInformation_Click() method, create a try/catch block.

      try
      {
      }
      catch
      {
      }


      Information entered into a web form is of type String. Because two of the fields within the Stock class are numerical, you will need to write code to convert the String values from the web form into numerical values. The try/catch statement helps protect your web application from crashing during the conversion due to type mismatch errors.

    3. Within the Try block, assign the value of the symbol field on the web form to the Symbol property of the Stock Object.

      temp.Symbol = symbol.Text;

    4. On the next line, assign the value of the price field on the web form to the Price property of the Stock Object. Convert the value from the web form to a Double before assignment.

      temp.Price = Convert.ToDouble(price.Text);
    5. Next, assign the value of the volume field on the web form to the Volume property of the Stock Object. Convert the value from the web form to an integer before assignment.

      temp.Volume = Convert.ToInt32(volume.Text);
    6. Outside of the try/catch block, add the Stock Object to the stockValues ArrayList.

      stockValues.Add(temp); 
    7. Update the value of stockValues currently held in Session.

      Session["stockValues"] = stockValues; 
    8. Finally, call the ConfigureCrystalReports() method. This will re-bind the report to the updated stockValues Object Collection.

      ConfigureCrystalReports(); 
    9. From the Build menu, click Build Solution.

      If you have any build errors, fix them now. 
    10. From the Debug menu, click Start Debugging.

      If no build errors appear, the Default.aspx page loads into your browser with three default values. To add additional values, fill in the TextBox Controls as appropriate and click the Add Stock Information button. The Report will dynamically update.

      When you run your web site, the report will load in your browser window with the three default values that you programmatically added in Exercise 4 Binding your Crystal Report to the Crystal Report Viewer. Above the report are three TextBox controls and a Button control. With these controls, you can dynamically update your Object Collection, and see the result of this update reflected in your report.

    11. Close the Internet Explorer window.

Take Microsoft software for a test drive. With MSDN Virtual Labs, you get full access to all available Microsoft products through 90-minute modules, each with its own downloadable manual. Try this lab out now.

Exercise 6: Adding Charts and Summary Information to the Report

Scenario

At this point, you have a fully functional web site that will display a Crystal report based off of an Object Collection. The site displays information that is programmatically entered into an Object Collection, as well as information that is added dynamically at run time.

In this exercise, you will add two charts, a calculated field, and summary information.

        Tasks            Detailed Steps   

  1. Adding a simple chart to the report.

    1. From the solution explorer, open StockObjects.rpt
    2. From the Crystal Reports menu, select Insert, and click Chart.
    3. In the Chart Expert dialog box, select a Pie chart.
    4. Select the Data tab.
    5. Select Stock.Symbol and click the top most Right Arrow to move the Stock.Symbol field to the On Change Of field.
    6. Select Stock.Volume and click the bottom most Right Arrow to move the Stock.Volume field to the Show Value(s) field. 
    7. Click OK.
    8. A new Report Header section is created, and a chart object is added to this section. 
    9. From the Debug menu, click Start Debugging.

      If no build errors appear, the Default.aspx page loads into your browser.

    10. Close the Internet Explorer window.
  2. Adding a chart based on a formula field. In this section, you will create a chart that reports off of aggregate information. You will first create a formula to calculate the worth of a particular holding, and then create a pie chart that displays the proportional worth of all of your holdings. 

    1. From the Crystal Reports menu, select Report, and click Formula Workshop.
    2. In the Formula Workshop dialog, select Formula Fields
    3. Click the New button to create a new formula.
    4. In the Formula Name dialog, enter worth. 
    5. Click Use Editor.
    6. Add code to multiply the value of the price field by the value of the volume field.

      {Stock.Volume}*{Stock.Price}
    7. Click Save and close.
    8. From the Crystal Reports menu, select Insert, and click Chart.
    9. In the Chart Expert dialog box, select a Pie chart.
    10. Click the Data tab.
    11. Select Stock.Symbol and click the top most Right Arrow to move the Stock.Symbol field to the On Change Of field.
    12. Select Worth and click the bottom most Right Arrow to move the Worth formula to the Show Value(s) field.
    13. Click the Text tab.
    14. Beside Title, clear the Auto-text checkbox. 
    15. Enter Worth / Symbol in the Title field.
    16. Click OK
    17. A new Report Header section is created, and a Chart Object is added to this

      section

      To re-position the objects within a Crystal report, drag them with your mouse and place them where you like. You can use the Main Report Preview button at the bottom of the form to display a preview of your report.

  3. Adding Formula and Summary fields to your report. In this section, you add a formula field to your report, and a summary field that will calculate the total value of your portfolio.

      1. Expand the Formula Fields node of the Field Explorer.

      2. Drag the worth formula onto your report. Position this field within the Details section of your report.

         
        If the Field Explorer is not visible, select Document Outline from the View menu. This field will display the worth of each row. Use a summary field to display the total worth of your portfolio.

      3.  From the Crystal Reports menu, select Insert, and click Summary.

        The Insert Summary dialog box appears.

      4.  Select the Worth formula from the Choose the Field to Summarize field.

      5. Select Sum from the Calculate this Summary field. 

      6. Select Grand Total from the Summary Location field.

      7. Click OK.

        A summary field is added to the report. 

      8.  From the Debug menu, click Start Debugging.

      9. If no build errors appear, the Default.aspx page loads into your browser. 

      10. Close the Internet Explorer window.

  4. Adding a pre-existing report. In this section, you will set your Web Application to use an existing report located on your file system.

      1. Right click on StockObjects.rpt in the Solution Explorer

      2. Click Delete

      3. Click OK in the dialog that pops up. 

      4. In Solution Explorer, right-click the web site name that is in bold type and then click Add Existing Item.

      5. In the Add Existing Item dialog, navigate to C:\Microsoft Hands-On-Lab\HOL-ILL05\Source\ Excercises and select the StockObjects.rpt file. 

      6. Click Add

      7. From the Debug menu, click Start Debugging

      8. If no build errors appear, the Default.aspx page loads into your browser and displays your new report.

      9. Close the Internet Explorer window.

Take Microsoft software for a test drive. With MSDN Virtual Labs, you get full access to all available Microsoft products through 90-minute modules, each with its own downloadable manual. Try this lab out now.

blog comments powered by Disqus
C# ARTICLES

- Beginning C#
- ASP.NET RedirectPermanent Method using C# an...
- C Programming Language and UNIX Pioneer Pass...
- Using Facebook JavaScript SDK in ASP.NET wit...
- ASP.NET Export to Excel and Word using VB.NE...
- WAV and MP3 Streaming with ASP.Net and C#
- Game Programming using SDL: the File I/O API
- C# and Java Developer Jobs on the Rise
- The Future Evolution of C# and VB.NET
- C# If and Else-if Statements
- How To Use the C# String Replace Method
- 5 Ways to Parse XML in C#
- C# Meets Design Patterns
- Coding a CRC-Generating Algorithm in C
- Cyclic Redundancy Check

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials