我会在数据进入报告之前使用 LINQ 来选择数据。我的代码在 VB.net 中,但可以很容易地翻译:
1 - 创建一个数据对象 - 将包含我们的数据
Public Class Animal
Public name As String
Public livesYears As Integer
Public location As String
End Class
2 - 创建 XtraReport1。将BindingSource 放到设计器上并将其设置为DataSource 到Animal。如果Animal 没有出现在向导生成的列表中,您将需要重新构建您的解决方案。将几个字段拖放到设计器上...“名称”等,以便报表有一些内容...报表!
3 - 创建 sub 以填充列表
Private Function createAnimals() As List(Of Animal)
Dim allAnimals As New List(Of Animal)
allAnimals.Add(New Animal With {.name = "Snake", .livesYears = "12", .location = "Africa"})
allAnimals.Add(New Animal With {.name = "Dog", .livesYears = "17", .location = "England"})
allAnimals.Add(New Animal With {.name = "Cat", .livesYears = "14", .location = "Egypt"})
allAnimals.Add(New Animal With {.name = "Hedgehog", .livesYears = "4", .location = "England"})
allAnimals.Add(New Animal With {.name = "Dragon", .livesYears = "350", .location = "Canada"})
allAnimals.Add(New Animal With {.name = "Bat", .livesYears = "28", .location = "Scotland"})
Return allAnimals
End Function
4 - 在表单加载中创建报表实例
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
'create our list of animals (could be a for loop that adds each dataset row to the list of Animal)
Dim allAnimals As List(Of Animal) = createAnimals()
'select just the Animals that we want
Dim justTheAnimalsIWant = (From ani In allAnimals
Where ani.location = "England"
Select ani).ToList
'create instance of the report
Dim report As New XtraReport1
'set the datasource to justTheAnimalsIWant
report.DataSource = justTheAnimalsIWant
Dim printTool As ReportPrintTool = New ReportPrintTool(report)
printTool.ShowPreview()
End Sub
上面的示例没有使用数据集,它使用了我们的Animal 对象列表。要填充我们的 Animal 对象列表,您可以使用 for 循环遍历数据行并添加到 Animal 对象列表中。然后在使用 LINQ 选择您想要的内容后,就像使用 justTheAnimalsIWant 一样。简单。