将 StockObjects 报表实例化为非嵌入式报表并将其绑定到 CrystalReportViewer 控件

“项目设置”中,您已经在 Web 或 Windows 窗体上放入了 CrystalReportViewer 控件。在上一过程中,您为项目添加了一个 StockObjects 报表。在本节中,将把 StockObjects 报表绑定到 Crystal Report 查看器,将报表的数据源设置为对象集合,并以编程方式填充该对象集合。

  1. 打开默认代码隐藏类 Default.aspx.cs 或 Default.aspx.vb。

  2. 在类签名之上,在类顶部添加 "Imports" [Visual Basic] 或 "using" [C#] 声明,以引用 System.Collections 命名空间。

<table>
<colgroup>
<col style="width: 100%" />
</colgroup>
<thead>
<tr class="header">
<th><img src="images/8yfdxzdx.alert_note(zh-cn,VS.90).gif" alt="Note" class="note" />注意</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td><p>通过此引用可访问 ArrayList 类。ArrayList 实现 ICollection。这会将 ArrayList 限定为几个类类型之一,可以使用这些类类型来生成 Crystal Reports 可识别的对象集合。</p></td>
</tr>
</tbody>
</table>

``` vb
Imports System.Collections
```

``` csharp
using System.Collections;
```
  1. 添加一个新的类级 ArrayList,并将其命名为 stockValues。
``` vb
Private stockValues As ArrayList
```

``` csharp
private ArrayList stockValues;
```
  1. 使用变量名 stockObjectsReport 为 ReportDocument 报表包装类添加新的类级声明。将其访问修饰符设置为 private。
``` vb
Private stockObjectsReport As ReportDocument
```

``` csharp
private ReportDocument StockObjectsReport;
```
  1. “项目设置”中创建的 ConfigureCrystalReports() 方法中,声明一个字符串变量,将其命名为 reportPath,然后将本地报表的运行时路径赋给它。将本地报表文件的名称作为字符串参数传递给 Server.MapPath() 方法。这会在运行时将本地报表映射到该文件路径。
``` vb
Dim reportPath As String = Server.MapPath("StockObjects.rpt")
```

``` csharp
string reportPath = Server.MapPath("StockObjects.rpt");
```
  1. 添加两行并实例化 ReportDocument 类。
``` vb
stockObjectsReport = New ReportDocument()
```

``` csharp
stockObjectsReport = new ReportDocument();
```
  1. 在下一行中,调用 ReportDocument 实例的 Load() 方法,并将 reportPath 字符串变量传递给它。

    Note注意

    ReportDocument 类是 CrystalDecisions.CrystalReports.Engine 命名空间的成员。在项目设置中为此命名空间添加了 "Imports" [Visual Basic] 或 "using" [C#] 声明。在实例化 ReportDocument 并加载某个报表时,可通过 SDK 获取该报表的访问权限。

    stockObjectsReport.Load(reportPath)
    
    stockObjectsReport.Load(reportPath);
    
  2. 接下来,将该报表的数据源设置为 stockValues ArrayList。

    stockObjectsReport.SetDataSource(stockValues)
    
    stockObjectsReport.SetDataSource(stockValues);
    
  3. 最后,将 CrystalReportViewer 的 ReportSource 属性绑定到 ReportDocument 实例。

``` vb
myCrystalReportViewer.ReportSource = stockObjectsReport
```

``` csharp
crystalReportViewer.ReportSource = stockObjectsReport;
```

现在,StockObjects 报表已绑定到 Crystal Report 查看器,并且该页显示正确的报表;不过,该报表当前绑定到空的数据源,因此,该报表没有要显示的信息。在下一节中,将使用示例数据以编程方式填充 stockValues ArrayList。