Crystal Reports Online Training

Learn Online, Anytime, Anywhere

Step-by-step online tutorials.

17.12 Manually Populate the Dataset

Manually Populated

Crystal Reports doesn’t have to print from an existing data source. It’s easy to report on data that is dynamically created as your application runs. There are a couple different ways where this can be useful. The first is reports based upon user input. For example, an application can have a user enter the details of a bank loan and it prints the amortization schedule. Since the input is dynamic, there is no database to print from. You have to calculate the amortization formulas that generate the data while the application is running and send it to the report for printing.

Another example is to manipulate data before it prints. Although Crystal Reports has a multitude of options for writing formulas and creatively using subreports, there are times when this doesn’t meet your needs. For example, a mailing label report could need to print each label a certain number of times. The number of times to print each one is stored in the database. It isn’t possible to use formulas or subreports to change the number of times a record is printed on a report. To create this report you would first create a new dataset. Then loop through the records in the original dataset while copying each record into the new dataset as many times as necessary. The report prints each label multiple times because there are multiple records for each one.

The DataSet class has methods to create a new dataset object within memory and populate it manually. Pass this manual dataset to Crystal Reports for printing. Listing 17-6 shows a simple example of how this is done. It creates a simple array with a customer’s Id and their last name. Then it builds a new DataTable object with two fields in it and adds it to the dataset. The last step is to copy the array into the dataset. Now it’s ready for printing!

Listing 17-6. Manually populating a dataset.
Private Sub FillDataset(ByVal myDataSet As DataSet)
Dim Customers(,) As String = {{"123", "Jones"}, {"456", "Smith"}}
' Create a new DataTable.
Dim myDataTable As DataTable = New DataTable("Customers")
Dim myDataColumn As DataColumn
Dim myDataRow As DataRow
' Create first column
myDataColumn = New DataColumn()
myDataColumn.DataType = System.Type.GetType("System.String")
myDataColumn.ColumnName = "CustomerID"
myDataTable.Columns.Add(myDataColumn)
' Create second column
myDataColumn = New DataColumn()
myDataColumn.DataType = System.Type.GetType("System.String")
myDataColumn.ColumnName = "LastName"
myDataTable.Columns.Add(myDataColumn)
myDataSet.Tables.Add(myDataTable)
'Copy the array into the datatable
Dim ixCustomers As Integer
For ixCustomers = 0 To 1
myDataRow = myDataTable.NewRow()
myDataRow("CustomerID") = Customers(ixCustomers, 0)
myDataRow("LastName") = Customers(ixCustomers, 1)
myDataTable.Rows.Add(myDataRow)
Next
End Sub