Walkthrough Creating and Modifying Report Layouts at Run Time

ActiveReports objects and controls are completely accessible at run time. The properties of any of the report sections or controls can be modified to produce a dynamic view of the report. The format event allows the properties of report sections and controls to be modified including height, visibility and other visual properties. The format event is the only event in which the printable area of a section can be modified. Once this event is completed, any changes to the section's height will not be reflected in the report output.

Note Controls may be added dynamically in the ReportStart event but should not be added dynamically after the ReportStart event fires as problems may result. This walkthrough illustrates how to create a report layout at run time based on user input.

This walkthrough is split up into the following activities:

• Adding an ActiveReport to a Visual Studio project

• Connecting the report to a data source

• Adding controls to the Windows Form to contain data

• Adding the data adapter to the Windows Form and generating a data set

• Adding code to the blank report

• Adding code to the Windows Form

• Adding code to the report's Detail_Format event

• Adding code to the report's ReportStart event

• Adding code to the Window Form's "Generate Report" button Click event

• Adding code to the Checked ListBox's SelectedIndexChanged event on the Windows Form

• Adding code to the Form_Load event

• Viewing the report

To complete the walkthrough, you must have access to the NorthWind database (NWind.mdb). When you have completed this walkthrough, you will have output that looks similar to the following.

Adding an ActiveReport to your project To add an ActiveReport to your project

1. Open a new project in Visual Studio.

2. Click on Project > Add New Item.

3. Select ActiveReports file and rename the file rptFieldsRT.

4. Click Open.

Connecting the report to a data source To connect the report to a data source

1. Click on the yellow report DataSource icon in the Detail section. This brings up the report DataSource dialog box.

3. Select "Microsoft Jet 4.0 OLE DB Provider" and click Next >>.

4. Click on the ellipsis to browse for the access path to Nwind.mdb. Click Open once you have selected the appropriate access path.

5. Click OK to continue.

6. In the Query field, type "Select * from products".

7. Click OK to return to the report design surface.

Adding controls to the Windows Form to contain data To add controls to the form

• Add the following controls to the Windows Form:

Control Panel

Label

Checked

ListBox

Button

CheckBox

Viewer

Dock Property

Left

Top Fill

Bottom Bottom Fill

Name Panel1

Text/Caption

(Empty string)

lblSelectFields Select Fields for Your Report clbFields btnGenRep chkGroup

Vieweri

Report Fields

Generate Report Group By Category ID (Empty string)

Misc Details

Height: 406 Width: 200 Location: Panel1 Location: Panel1

Location: Panel1 Location: Panel1

Location: Windows Form

Adding a data adapter to the Windows Form and generating the dataset To add a data adapter to the form

1. On the Data toolbox, double-click OleDbDataAdapter.

2. This adds the adapter to the Windows Form and opens the Data Adapter Configuration Wizard.

3. Follow the instructions to choose the data connection, select the data provider, select the database and enter the SQL statement, "SELECT CategoryID, Discontinued, ProductID, ProductName, QuantityPerUnit, ReorderLevel, SupplierID, UnitPrice, UnitsInStock, UnitsOnOrder FROM Products" (For help with this, see "Connecting the report to a data source" above.

4. Click "Finish" to return to the Windows Form. To generate the dataset

1. Click on Data > Generate Dataset... on the Visual Studio menu bar.

Configure Data Adapter..

2. This opens the Generate Dataset dialog.

3. Click New and make sure the selected table to be added to the data set is Products.

4. Check "Add this dataset to the designer" and click OK.

Adding code to the blank ActiveReport To add code to the blank report

• Insert the following code beneath "ActiveReports Designer generated code."

[Visual Private

Basic] m_arrayFields

As ArrayListPublic WriteOnly Property FieldsList() As ArrayList Set(ByVal Value As ArrayList)

m_arrayFields = Value

End Set End Property

Private m_useGroups As BooleanPublic WriteOnly Property UseGroups() As Boolean Set(ByVal Value As Boolean)

m_useGroups = False m_useGroups = Value

End Set End Property

Private Sub constructReport() Try

Me.Detail.CanGrow = True Me.Detail.CanShrink = True Me.Detail.KeepTogether = True If m_useGroups = True Then

Me.Sections.InsertGroupHF()

CType(Me.Sections("GroupHeader1"), GroupHeader)._

DataField = "CategoryID" Me.Sections("GroupHeader1").BackColor = System.Drawing.Color. SlateBlue

Me.Sections("GroupHeader1").CanGrow = True Me.Sections("GroupHeader1").CanShrink = True

CType(Me.Sections("GroupHeader1"), GroupHeader).RepeatStyle =

RepeatStyle.OnPageIncludeNoDetail Me.Sections("GroupHeader1").Height = 0 Dim txt As New TextBox()

txt txt txt txt txt

DataField = "CatagoryID"

Location = New System.Drawing.PointF(0.0F, Width = 2.0F Height = 0.3F

Style = "font-weight: bold; font-size: 16pt

End For

_arrayField

Me.Sections("GroupHeader1").Controls.Add(txt) To m_arrayFields.Count - 1

If (m_useGroups = False) Or (m_useGroups AndAlso ToString <> "CategoryID") Then Dim lbl As New Label() lbl.Text = m_arrayFields(i) + ":"

lbl.Location() = New System.Drawing.PointF(0.0F, m_c lbl.Width = 0.9F

lbl.Height = m_defaultHeight

Me.Detail.Controls.Add(lbl)

Dim txt As New TextBox()

txt.DataField = m_arrayFields(i)

txt.Location = New System.Drawing.PointF(1.0F, m_cu. txt.Width = m_defaultWidth txt.Height = m_defaultHeight Me.Detail.Controls.Add(txt) If m_arrayFields(i) = "UnitPrice" Then txt.OutputFormat = "$#.00"

End If m_currentY = m_currentY + m_defaultHeight

End If

Next

Catch ex As Exception

System.Windows.Forms.MessageBox.Show("Error in Report-constructReport: " + ex.Message, "Project Error", System.Windows.Forms.Message System.Windows.Forms.MessageBoxIcon.Error)

End Try

End Sub

private ArrayList m_arrayFields;

public ArrayList FieldsList {

set{m_arrayFields value;

private bool m_useGroups = false;

public bool UseGroups {

set{m_useGroups = value;

float m_defaultHeight = .2f; float m_defaultWidth = 4f; float m_currentY = 0f;

private void constructReport() {

this.Detail

CanGrow = true; this.Detail.CanShrink = true; this.Detail.KeepTogether = true;

if(m_useGroups) {

this.Sections.InsertGroupHF() ((GroupHeader)this.Sections["

"CategoryID"; this.Sections["GroupHeader1"]

Color.SlateBlue; this.Sections["GroupHeader1"] this.Sections["GroupHeader1"] ((GroupHeader)this.Sections["

RepeatStyle.OnPageIncludeNoDetail; this.Sections["GroupFooter1"].Height = 0; TextBox txt = new TextBox();

GroupHeader1"]).DataField =

.BackColor = System.Drawing.

.CanGrow = true; .CanShrink = true; GroupHeader1"]).RepeatStyle =

txt txt txt txt txt

"CategoryID"; new System.Drawing.PointF(0f,0);

DataField Location Width =2f; Height = .3f;

Style = "font-weight: bold;

font-size: 16pt;' this.Sections["GroupHeader1"].Controls.Add(txt);

useGroups || (m_useGroups && m_arrayFields[i].ToString( != "CategoryID"))

lbl.Text = m_arrayFields[i].ToString() + ":";

lbl.Location = new System.Drawing.PointF(0f,m_currei lbl.Width =.9f;

lbl.Height = m_defaultHeight;

this.Detail.Controls.Add(lbl);

TextBox txt = new TextBox();

txt.DataField = m_arrayFields[i].ToString();

txt.Location = new System.Drawing.PointF(1f,m_curren txt.Width =m_defaultWidth;

txt.Height = m_defaultHeight;

this.Detail.Controls.Add(txt);

m_currentY = m_currentY + m_defaultHeight;

catch(Exception ex) {

System.Windows.Forms.MessageBox.Show("Error in Report-constructReport: " + ex.Message,"Project Error",System.Windows.Forms. MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Err

Adding code to the Windows Form

To add code to the form

• Insert the following code beneath "ActiveReports Designer generated code."

[Visual Basic] Private Sub fillCheckBox()

For i = 0 To Me.DataSetll.Tables.Count - 1

For c = 0 To Me.DataSet11.Tables(i).Columns.Count - 1

Me.clbFields.Items.Add(Me.DataSet11.Tables(i).Columns(c)._ ColumnName)

Next

Next

End Sub

Private Sub launchReport()

Dim rpt As New rptFieldsRT() Try rpt.FieldsList = m_arrayField rpt.ds.SQL = Me.OleDbDataAdapter1.SelectCommand.CommandText rpt.ds.ConnectionString = Me.OleDbConnection1.ConnectionString Viewer1.Document = rpt.Document rpt.Run() Catch ex As Exception

System.Windows.Forms.MessageBox.Show(Me, "Error in launchReport: " _

+ ex.Message, "Project Error", MessageBoxButtons.OK, MessageBoxlcon.Err

End Try

End Sub

static void Main() {

Application.Run(new Form1());

private string getDatabasePath() {

RegistryKey regKey = Registry.LocalMachine;

regKey = regKey.CreateSubKey("SOFTWARE\\Data Dynamics\\ActiveReports.NET

\\SampleDB"); return (string)regKey.GetValue("");

private void fillCheckBox() {

for(int i=0;i<this.dataSet11.Tables.Count;i++) {

for(int c=0;c<this.dataSet11.Tables[i].Columns.Count;c++) {

this.clbFields.Items.Add(this.dataSet11.Tables[i].Columns[c]

ArrayList m_arrayField = new ArrayList();

private void launchReport() {

rptFieldsRT rpt = new rptFieldsRT(); rpt.FieldsList = m_arrayField;

rpt.ds.SQL = this.oleDbDataAdapter1.SelectCommand.CommandText; rpt.ds.ConnectionString = this.oleDbConnection1.ConnectionString; this.viewer1.Document = rpt.Document; rpt.Run();

catch(Exception ex) {

MessageBox.Show(this,"Error in launchReport: " + ex.Message,"Project Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

Adding code to the Detail_Format event To write the code in Visual Basic

• Right-click in any section of the design window of rptFieldsRT, and click on View Code to display the code view for the report. At the top left of the code view for rptFieldsRT, click the drop-down arrow and select Detail. At the top right of the code window, click the drop-down arrow and select Format. This creates an event-handling method for rptFieldsRT's Detail_Format event.

To write the code in C#

• Click in the Detail section of rptFieldsRT to select the section. Click on the events icon in the Properties window to display available events for the section. Double-click Format. This creates an event-handling method for rptFieldsRT's Detail_Format event.

The following example shows what the code for the method looks like:

[Visual Basic] Dim m_default Height As Single = 0.2 Dim m_default Width As Single = 4 Dim m_currentY As Single = 0 Dim i As Integer Dim m_count As Integer

Private Sub Detail_Format(ByVal sender Handles Detail.Format

Me.Detail.BackColor

Else

Me.Detail.BackColor

int m_count;

private void Detail_Format(object sender, {

this.Detail.BackColor

this.Detail.BackColor

Adding code to the ReportStart event To write the code in Visual Basic

• Right-click in any section of the design window of rptFieldsRT, and click on View Code to display the code view for the report. At the top left of the code view for rptFieldsRT, click the drop-down arrow and select (Base Class Events). At the top right of the code window, click the drop-down arrow and select ReportStart. This creates an event-handling method for rptFieldsRT's ReportStart event.

To write the code in C#

• Click in the gray area below rptFieldsRT to select the report. Click on the events icon in the Properties window to display available events for the report. Double-click ReportStart. This creates an event-handling method for rptFieldsRT's ReportStart event.

The following example shows what the code for the method looks like:

[Visual Basic]

Private Sub rptFieldsRT_ReportStart(ByVal sender As Object, ByVal e As _

As Object, ByVal e As System.EventArgs)

= System.Drawing.Color.SlateGray = System.Drawing.Color.DarkSeaGreen

System.EventArgs eArgs)

= System.Drawing.Color.SlateGray;

= System.Drawing.Color.DarkSeaGreen;

System.EventArgs) Handles MyBase.ReportStart constructReport()

private void rptFieldsRT_ReportStart(object sender, System.EventArgs eArgs) {

constructReport();

Adding code for btnGenRep's Click event To write the code in Visual Basic

• Double-click on btnGenRep. This creates an event-handling method for btnGenRep's Click event following code to the btnGenRep_Click event.

To write the code in C#

• Double-click on btnGenRep. This creates an event-handling method for btnGenRep's Click event following code to the btnGenRep_Click event.

The following example shows what the code for the method looks like:

[Visual Basic]

Private Sub btnGenRep_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGenRep.Click Me.m_arrayField.Clear()

For i = 0 To Me.clbFields.Checkedltems.Count - 1

m_arrayField.Add(Me.clbFields.CheckedItems(i).ToString)

Next launchReport()

private void btnGenRep_Click(object sender, System {

this.m_arrayField.Clear();

for(int i=0;i<this.clbFields.CheckedItems {

m_arrayField.Add(this.clbFields

launchReport();

Adding code to the clbFields_SelectedIndexChanged event To write the code in Visual Basic

• Right-click in any section of the Windows Form, and click on View Code to display the code view for the Windows Form. At the top left of the code view for the form, click the drop-down arrow and select clbFields. At the top right of the code window, click the drop-down arrow and select SelectedIndexChanged. This creates an event-handling method for the Form1_SelectedIndexChanged event.

To write the code in C#

• Click in the designer window of the Windows Form to select it. Click on the events icon in the Properties window to display available events for the section. Double-click SelectedIndexChanged. This creates an event-handling method for the Form1_SelectedIndexChanged event.

The following example shows what the code for the method looks like:

[Visual Basic]

Private Sub clbFields_SelectedIndexChanged(ByVal sender As Object, ByVal e _ As System.EventArgs) Handles CheckedListBoxl.SelectedIndexChanged If Me.clbFields.CheckedItems.Count < 0 Then Me.btnGenRep.Enabled = False

Else

.CheckedItems[i].ToString());

Me.btnGenRep.Enabled = True End If

private void clbFields_SelectedIndexChanged(object sender, System.EventArgs e) {

if(this.clbFields.CheckedItems.Count>0) {

this.btnGenRep.Enabled = true;

this.btnGenRep.Enabled = false;

Adding code to the Form1_Load event To write the code for the viewer in Visual Basic

• Right-click on Form1, and click on View Code to display the code view for the form. At the top left of the code view for Form1, click the drop-down arrow and select (Base Class Events). At the top right of the code window, click the drop-down arrow and select Load. This creates an event-handling method for the Form1_Load event. Add code to the handler to:

• Format the viewer to show the report when it is run

To write the code for the viewer in C#

• Click on the blue section at the top of Form1 to select the form. Click on the events icon in the Properties window to display available events for Form1. Double-click Load. This creates an event-handling method for the Form1_Load event. Add code to the handler to:

• Format the viewer to show the report when it is run

The following example shows what the code for the method looks like:

[Visual Basic] Dim i As Integer Dim c As Integer

Dim m_arrayField As New ArrayList()

Private Sub Forml_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles MyBase.Load Try

Me.OleDbConnectionl.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;_

Data Source=C:\Program Files\Data Dynamics\ActiveReports.NET\Data\NWIN] MDB;Persist Security Info=False" Me.OleDbDataAdapterl.Fill(Me.DataSetll) fillCheckBox() Catch ex As Exception

System.Windows.Forms.MessageBox.Show(Me, "Error in Form_Load: " + ex.Message, "Project Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

End Sub

private {

string m_dbPath = getDatabasePath();

this.oleDbConnectionl.ConnectionString = "Provider=Microsoft.Jet.OLEDB Data Source=" + m_dbPath + "\\NWIND.MDB;Persist Security Info this.oleDbDataAdapterl.Fill(this.dataSetll); fillCheckBox();

catch(Exception ex) {

void Form1_Load(object sender, System.EventArgs e)

MessageBox.Sho¥(this,"Error in Form_Load: " + ex.Message,"Project Error MessageBoxButtons.OK,MessageBoxIcon.Error);

Viewing the report To view the report

1. Add the ActiveReports viewer control to a Windows Form.

2. Add the code needed to set the viewer document equal to the report document. See Using the ActiveReports WinForm Viewer for help.

Was this article helpful?

0 0

Post a comment