ActiveReports使用教程:在运行时将页面报表绑定到数据源

ActiveReports允许您在运行时修改数据源。请参阅以下示例代码集,以在运行时将Page报表或RDL报表连接到数据源。

ActiveReports 是一款专注于 .NET 平台的报表控件,全面满足 HTML5、WinForm、ASP.NET、.NET Core、WPF 等平台下的中国式复杂报表设计和跨平台报表开发需求,作为专业的报表工具为全球超过 300,000 名开发者提供全面的报表解决方案。

ActiveReports正式版

ActiveReports允许您在运行时修改数据源。请参阅以下示例代码集,以在运行时将Page报表或RDL报表连接到数据源。

连接到OleDB数据源

使用API在运行时在报表上设置数据源和数据集。这些步骤假定您已经添加了页面报表模板,并将Viewer控件放置在Visual Studio项目中的Windows窗体上。

注意:可以将以下代码示例用于SQL,Odbc或OleDB数据源绑定。为此,请根据数据源修改数据提供者类型和连接字符串。
1、从Visual Studio工具箱中,将“表”数据区域拖放到报表的设计图面上。

2、在表中,选择以下单元格,然后转到“属性窗口”以设置其“值”属性。

单元格 值属性
左单元格 =Fields!ProductID.Value
中间单元格 =Fields!InStock.Value
右单元格 =Fields!Price.Value

3、转到“ Visual Studio报表”菜单,然后选择“保存布局”。

4、在出现的“另存为”窗口中,导航到项目的文件夹,然后将布局(如RuntimeBinding.rdlx)保存在bin / debug文件夹中。
5、双击Windows窗体的标题栏,为Form_Load事件创建事件处理方法。

6、将以下代码添加到处理程序中,以连接到数据源,添加数据集并在报表中提供数据。

Visual Basic.NET代码粘贴到Form_Load事件中。

'create an empty page reportDim def As New PageReport'load the report layoutdef.Load(New System.IO.FileInfo(Application.StartupPath + "RuntimeBinding.rdlx"))'create and setup the data sourceDim myDataSource As New GrapeCity.ActiveReports.PageReportModel.DataSourcemyDataSource.Name = "Example Data Source"myDataSource.ConnectionProperties.DataProvider = "OLEDB"myDataSource.ConnectionProperties.ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[User folder]Samples14DataReels.mdb"'setup the datasetDim myDataSet As New GrapeCity.ActiveReports.PageReportModel.DataSet()Dim myQuery As New GrapeCity.ActiveReports.PageReportModel.Query()myDataSet.Name = "Example Data Set"myQuery.DataSourceName = "Example Data Source"myQuery.CommandType = GrapeCity.ActiveReports.PageReportModel.QueryCommandType.TableDirectmyQuery.CommandText = GrapeCity.ActiveReports.Expressions.ExpressionInfo.FromString("Product")myDataSet.Query = myQuery' add fieldsDim _field As New GrapeCity.ActiveReports.PageReportModel.Field("ProductID", "ProductID", Nothing)myDataSet.Fields.Add(_field)_field = New GrapeCity.ActiveReports.PageReportModel.Field("InStock", "InStock", Nothing)myDataSet.Fields.Add(_field)_field = New GrapeCity.ActiveReports.PageReportModel.Field("Price", "Price", Nothing)myDataSet.Fields.Add(_field)'bind the data source and the dataset to the reportdef.Report.DataSources.Add(myDataSource)def.Report.DataSets.Add(myDataSet)Viewer1.LoadDocument(def.Document)

C#代码粘贴到Form_Load事件中。

//create an empty page reportGrapeCity.ActiveReports.PageReport def = new GrapeCity.ActiveReports.PageReport();//load the report layoutdef.Load(new System.IO.FileInfo(Application.StartupPath + "RuntimeBinding.rdlx"));//create and setup the data sourceGrapeCity.ActiveReports.PageReportModel.DataSource myDataSource = new GrapeCity.ActiveReports.PageReportModel.DataSource();myDataSource.Name = "Example Data Source";myDataSource.ConnectionProperties.DataProvider = "OLEDB";myDataSource.ConnectionProperties.ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=[User folder]\Samples14\Data\Reels.mdb";//setup the datasetGrapeCity.ActiveReports.PageReportModel.DataSet myDataSet = new GrapeCity.ActiveReports.PageReportModel.DataSet();GrapeCity.ActiveReports.PageReportModel.Query myQuery = new GrapeCity.ActiveReports.PageReportModel.Query();myDataSet.Name = "Example Data Set";myQuery.DataSourceName = "Example Data Source";myQuery.CommandType = GrapeCity.ActiveReports.PageReportModel.QueryCommandType.TableDirect;myQuery.CommandText = GrapeCity.ActiveReports.Expressions.ExpressionInfo.FromString("Product");myDataSet.Query = myQuery;// add fieldsGrapeCity.ActiveReports.PageReportModel.Field _field = newGrapeCity.ActiveReports.PageReportModel.Field("ProductID", "ProductID", null);myDataSet.Fields.Add(_field);_field = new GrapeCity.ActiveReports.PageReportModel.Field("InStock", "InStock", null);myDataSet.Fields.Add(_field);_field = new GrapeCity.ActiveReports.PageReportModel.Field("Price", "Price", null);myDataSet.Fields.Add(_field);//bind the data source and the dataset to the reportdef.Report.DataSources.Add(myDataSource);def.Report.DataSets.Add(myDataSet);def.Run();viewer1.LoadDocument(def.Document);

7、按F5键运行该应用程序。

连接到未绑定的数据源

要在运行时连接到未绑定的数据源,可以将DataSet提供程序或Object提供程序与LocateDataSource事件一起使用。 当报告引擎需要输入数据以使用时,报告引擎将引发LocateDataSource事件。

数据集提供者

使用DataSet提供程序,ConnectionString和Query设置会根据您连接数据的方式而有所不同。

要使用LocateDataSource事件将报表绑定到数据,请将ConnectionString留空。

  • 如果LocateDataSource返回数据集,则将查询设置为数据集表名称。
  • 如果LocateDataSource返回DataTable或DataView,则查询保留为空。

要将报表绑定到文件中的数据集,请将ConnectionString设置为文件的路径,并将Query设置为DataSet表名。

数据集提供者的局限性

  • 不支持其中包含句点的关系名称。
  • 嵌套关系中的字段仅遍历父关系(例如FK_Order_Details_Orders.FK_Orders_Customers.CompanyName)。

父表字段

要从父表中请求字段,请在字段名称前添加必须遍历的关系名称才能导航到适当的父表。 字段名称和与句点的关系要分开。

例如,考虑一个名为OrderDetails的主表,它具有一个名为Orders的父表。 名为Orders_OrderDetails的关系定义了两个表之间的关系。 使用具有以下语法的字段从父表访问OrderDate:

Orders_OrderDetails.OrderDate

使用相同的技术遍历表关系的多个级别。 例如,考虑在先前示例中使用的Orders表具有一个名为Customers的父表,以及一个将这两个表绑定在一起的关系,称为Customers_Orders。 如果CommandText将主表指定为OrderDetails,请使用以下语法从父表获取CustomerName字段:

Customers_Orders.Orders_OrderDetails.CustomerName

注意:如果字段和关系具有相同的名称,则可能会出现歧义。 不支持。

使用数据集提供程序

您可以使用API在运行时在报表上设置数据集。

数据集提供程序返回一个数据表。 数据表中的所有字段均可用。 要将数据集提供程序用作报表的数据源,请设置报表定义和运行时,然后将页面文档附加到LocateDataSourceEventHandler。

这些步骤假定您已经添加了页面报表模板,并将Viewer控件放置在Visual Studio项目中的Windows窗体上。

1、在报表资源管理器中,转到“数据源”节点,然后右键单击以选择“添加数据源”。

2、在出现的“报表数据源”对话框中,将“类型”设置为DataSetProvider并关闭对话框。数据源节点出现在ReportExplorer中。

3、右键单击数据源节点,然后选择添加数据集

4、在出现的“数据集”对话框中,选择“字段”页面。

5、在“字段”页面上,添加一个字段,例如= Fields!ProductID.Value和= Fields!InStock.Value。
6、单击“确定”关闭对话框。具有字段名称的节点出现在数据集名称下方。

7、从Visual Studio工具箱的ActiveReports 14 Page Report选项卡中,将Table数据区域拖到报表的设计图面上。

8、在ReportExplorer中,将新添加的字段添加到表的详细信息行中的单元格上,并保存报告。

9、在Visual Studio解决方案资源管理器中,右键单击YourProjectName,然后选择“添加”>“类”。

10、在出现的“添加新项”窗口中,将该类重命名为DataLayer.cs或.vb,然后单击“添加”。

11、在解决方案资源管理器中,双击DataLayer.cs或.vb以打开该类的代码视图,并将以下代码粘贴到该类中。

Visual Basic.NET代码粘贴到DataLayer类中。

Imports GrapeCity.ActiveReports.Expressions.ExpressionObjectModelImports System.GlobalizationImports System.Data.OleDbFriend NotInheritable Class DataLayer    Private _datasetData As System.Data.DataSet    Public Sub New()        LoadDataToDataSet()    End Sub    Public ReadOnly Property DataSetData() As System.Data.DataSet        Get           Return _datasetData        End Get    End Property    Private Sub LoadDataToDataSet()        Dim connStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;                Data Source=[User folder]\Samples14\Data\Reels.mdb"        Dim productSql As String = "SELECT top 100 * FROM Product"        _datasetData = New DataSet()        Dim conn As New OleDbConnection(connStr)        Dim cmd As OleDbCommand = Nothing        Dim adapter As New OleDbDataAdapter       cmd = New OleDbCommand(productSql, conn)       adapter.SelectCommand = cmd       adapter.Fill(_datasetData, "Products")    End SubEnd Class

C#代码粘贴到DataLayer类中。

using System;using System.Data;using System.Data.OleDb;internal sealed class DataLayer{    private DataSet dataSetData;        public DataLayer()        {                LoadDataToDataSet();        }        public DataSet DataSetData        {                get { return dataSetData; }        }                private void LoadDataToDataSet()        {        string connStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;                Data Source=[User folder]\Samples14\Data\Reels.mdb";        string productSql = "SELECT * From Product";                dataSetData = new DataSet();        OleDbConnection conn = new OleDbConnection(connStr);        OleDbCommand cmd = new OleDbCommand(productSql, conn);        OleDbDataAdapter adapter = new OleDbDataAdapter();        adapter.SelectCommand = cmd;        adapter.Fill(dataSetData, "Products");        }}

注意:DataSetDataSource示例提供了有关如何创建DataLayer类的上下文,以下代码中使用了该类。 可以从GitHub下载DataSetDataSource示例。 请参阅此处的示例说明。

12、双击Windows窗体的标题栏,为Form_Load事件创建事件处理方法,然后将以下代码添加到处理程序中。

Visual Basic.NET代码粘贴到Form_Load事件中。

LoadReport()  

Visual Basic.NET代码将INSIDE粘贴在表单的类声明中。

Dim WithEvents runtime As GrapeCity.ActiveReports.Document.PageDocumentPrivate Sub LoadReport()    Dim rptPath As New System.IO.FileInfo("....YourReportName.rdlx")    'Create a report definition that loads an existing report.    Dim definition As New GrapeCity.ActiveReports.PageReport(rptPath)    'Load the report definition into a new page document.    runtime = New GrapeCity.ActiveReports.Document.PageDocument(definition)    'Attach the runtime to an event. This line of code creates the event shell below.    Viewer1.LoadDocument(runtime)End Sub'ActiveReports raises this event when it cannot locate a report's data source in the usual ways.Private Sub runtime_LocateDataSource(ByVal sender As Object, ByVal args As GrapeCity.ActiveReports.LocateDataSourceEventArgs) Handles Runtime.LocateDataSource    Dim dl = New DataLayer    args.Data = dl.DataSetData.Tables("Products")End Sub

C#代码粘贴到Form_Load事件中。

LoadReport(); 

C#代码将INSIDE粘贴在表单的类声明中。

private void LoadReport(){   System.IO.FileInfo rptPath = new System.IO.FileInfo("..\..\YourReportName.rdlx");   //Create a report definition that loads an existing report.   GrapeCity.ActiveReports.PageReport definition = new GrapeCity.ActiveReports.PageReport(rptPath);   //Load the report definition into a new page document.   GrapeCity.ActiveReports.Document.PageDocument runtime = new GrapeCity.ActiveReports.Document.PageDocument(definition);   //Attach the runtime to an event. This line of code creates the event shell below.   runtime.LocateDataSource += new GrapeCity.ActiveReports.LocateDataSourceEventHandler(runtime_LocateDataSource);   viewer1.LoadDocument(runtime);}//ActiveReports raises this event when it cannot locate a report's data source in the usual ways.private void runtime_LocateDataSource(object sender, GrapeCity.ActiveReports.LocateDataSourceEventArgs args){   DataLayer dl = new DataLayer();   args.Data = dl.DataSetData.Tables["Products"];}

对象提供者

使用API将报表数据源绑定到对象集合。要将对象提供程序绑定到报表,请设置报表定义和页面文档,然后将页面文档附加到LocateDataSourceEventHandler。创建一个公共类,该公共类设置可以与数据字段绑定的属性名称。

对象提供者数据源必须具有查询保留为空白且与对象提供者数据源的字段相对应的字段的数据集。在“字段”下的“数据集”对话框中手动添加这些字段。

使用对象提供程序时,请始终将报表的ConnectionString留空,因为它使用LocateDataSource事件绑定到对象。将查询设置为以下值之一:

使用对象提供者

这些步骤假定您已经添加了页面报表模板,并将Viewer控件放置在Visual Studio项目中的Windows窗体上。

1、在报表资源管理器中,转到“数据源”节点,然后右键单击以选择“添加数据源”

2、在出现的“报表数据源”对话框中,将“类型”设置为ObjectProvider并关闭对话框。数据源节点出现在ReportExplorer中。

3、右键单击数据源节点,然后在出现的“数据集”对话框中选择“字段”页面。

4、在“字段”页面中,添加一个== Fields!name.Value之类的字段,然后单击“确定”关闭对话框。具有字段名称的节点将出现在数据集名称下方。

5、从Visual Studio工具箱的ActiveReports 14 Page Report选项卡中,将Table数据区域拖到报表的设计图面上。

6、在ReportExplorer中,将新添加的字段添加到表的详细信息行中的单元格上。

7、将报告另存为DogReport.rdlx。

8、在解决方案资源管理器中,右键单击表单,然后选择查看代码以打开代码视图。

9、在窗体的“代码视图”中,将以下代码粘贴到类声明中。

Visual Basic.NET代码将INSIDE粘贴在表单的类声明中。

' Create a class from which to call a property.Public Class dog   Private _name As String   Public Property name() As String      Get         Return _name      End Get      Set(ByVal value As String)         _name = Value      End Set   End PropertyEnd Class' Create an array to contain the data.Dim dogArray As System.Collections.ArrayList' Create a method to populate the data array.Private Sub LoadData()   dogArray = New System.Collections.ArrayList()   Dim dog1 As New dog()   dog1.name = "border collie"   dogArray.Add(dog1)   dog1 = New dog()   dog1.name = "cocker spaniel"   dogArray.Add(dog1)   dog1 = New dog()   dog1.name = "golden retriever"   dogArray.Add(dog1)   dog1 = New dog()   dog1.name = "shar pei"   dogArray.Add(dog1)End Sub

C#代码将INSIDE粘贴在表单的类声明中。

// Create a class from which to call a property.public class dog{   private string _name;   public string name  {      get { return _name; }      set { _name = value; }   }}// Create an array to contain the data.System.Collections.ArrayList dogArray;// Create a method to populate the data array.private void LoadData(){   dogArray = new System.Collections.ArrayList();   dog dog1 = new dog();   dog1.name = "border collie";   dogArray.Add(dog1);   dog1 = new dog();   dog1.name = "cocker spaniel";   dogArray.Add(dog1);   dog1 = new dog();   dog1.name = "golden retriever";   dogArray.Add(dog1);   dog1 = new dog();   dog1.name = "shar pei";   dogArray.Add(dog1);}  

10、设置报告并为LocateDataSource事件添加处理程序。

Visual Basic.NET代码粘贴到Form_Load事件中。

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load   ' Create file info with a path to the report in your project.   Dim fi As New System.IO.FileInfo("..\..\DogReport.rdlx")   ' Create a report definition using the file info.   Dim repDef As New GrapeCity.ActiveReports.PageReport(fi)   ' Create a page document using the report definition.   Dim runt As New GrapeCity.ActiveReports.Document.PageDocument(repDef)   ' Create a LocateDataSource event for the runtime.   AddHandler runt.LocateDataSource, AddressOf runt_LocateDataSource  ' Display the report in the viewer. The title can be any text.   Viewer1.LoadDocument(runt)End Sub

C#代码粘贴到Form_Load事件中。

private void Form1_Load(object sender, EventArgs e){   // Create file info with a path to the report in your project.   System.IO.FileInfo fi = new System.IO.FileInfo("..\..\DogReport.rdlx");   // Create a report definition using the file info.   GrapeCity.ActiveReports.PageReport repDef = new GrapeCity.ActiveReports.PageReport(fi);   // Create a page document using the report definition.   GrapeCity.ActiveReports.Document.PageDocument runt = new GrapeCity.ActiveReports.Document.PageDocument(repDef);   // Create a LocateDataSource event for the runtime.   runt.LocateDataSource += new GrapeCity.ActiveReports.LocateDataSourceEventHandler(runt_LocateDataSource);   // Display the report in the viewer. The title can be any text.   viewer1.LoadDocument(runt);}

11、使用LocateDataSource事件从对象加载数据。

Visual Basic.NET代码将INSIDE粘贴在表单的类声明中。

Private Sub runt_LocateDataSource(ByVal sender As Object, ByVal args As GrapeCity.ActiveReports.LocateDataSourceEventArgs)   If dogArray Is Nothing Then LoadData()   args.Data = dogArrayEnd Sub

C#代码将INSIDE粘贴在表单的类声明中。

void runt_LocateDataSource(object sender, GrapeCity.ActiveReports.LocateDataSourceEventArgs args){   if (dogArray == null)   {      LoadData();   }   args.Data = dogArray;}  

12、按F5运行该应用程序。

相关内容推荐:

试用下载>>>

ActiveReports使用教程>>>


想要购买ActiveReports正版授权,或了解更多产品信息请点击【咨询在线客服】

ActiveReports使用教程:在运行时将页面报表绑定到数据源

标签:

来源:慧都

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2020年4月9日
下一篇 2020年4月9日

相关推荐

发表回复

登录后才能评论