O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.16. Dynamically Creating Crystal Reports

Problem

You need to define a DataTable at runtime and bind it to a Crystal Report.

Solution

Create a DataAdapter and use it to fill a DataTable with a subset of records (specified by a range of OrderID values, from the Orders table joined to Order Details records from the Northwinds sample database demonstrated in the following example). Create a new report document and set its data source to the DataTable. To display the report, set the source of the report view to the report document.

The C# code is shown in Example 7-32.

Example 7-32. File: CrystalReportsForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using System.Data; using System.Data.SqlClient; private CrystalDecisions.Windows.Forms.CrystalReportViewer crv; // . . . // Get the user entered OrderID range. int orderIdFrom, orderIdTo; try { orderIdFrom = Convert.ToInt32(orderIdFromTextBox.Text); orderIdTo = Convert.ToInt32(orderIdToTextBox.Text); } catch (Exception ex) { MessageBox.Show(ex.Message, "Dynamic Crystal Reports", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Cursor.Current = Cursors.WaitCursor; // Create a DataAdapter and fill the table. String sqlText = "SELECT * FROM Orders " + "JOIN [Order Details] Order_Details ON Orders.OrderID = " + "Order_Details.OrderID " + "WHERE Orders.OrderID BETWEEN " + orderIdFrom + " AND " ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required