TeeChart Pro Tutorials

Welcome to TeeChart Pro ActiveX Version 2017 tutorials

Copyright © Steema Software SL. 1998-2017. All Rights Reserved.
Some Tutorials and menu options contain ActiveX objects best viewed with Internet Explorer.


Tutorial 1 - Getting started

Getting Started - building Charts and populating Data Series

Contents

Introduction

Building a Chart

Including TeeChart on a Form

The Chart Editor

The Chart Series Gallery

Populate the new data Series

ADO
Coded data input

Selecting a Series type to suit your needs

Introduction

Basic Charts can be built and implemented using the Chart Editor with little or no use of code. The Chart Editor is two Editors in one, the Chart may be thought of as being distinct from its data Series contents. You may define the Chart appearance, titles, Legend characteristics and 3D aspect without having to include a data Series. That gives you the freedom to add and remove different data Series types at runtime without having to redefine the whole Chart look and feel.

These components work together, with Chart axes being the interface between Chart and Series. A Series has data and its values will influence the label characteristics of the Chart axes. The axes appearance, colours, grid frequency and label fonts may all be defined for the Chart before adding data Series. TeeChart will make a best estimate of most values to minimise the need for you to predefine Chart and Series properties.
Add multiple series types with the Chart editor The "Chart distinct from Series" design paradigm of TeeChart allows you to mix a variety of Series types without being limited to a choice of predefined Chart formats.

And Internet ! For this area of growing demand for applications, feature include JPEG, PNG, GIF and PCX Chart save to file or stream and TeeChart "tee" templates for low bandwidth charting. TeeChart fully supports Internet Information Server's Active Server Pages (ASP) and tee template technology allows for the distribution of Live OLE/ODBC database Charting applications without the need for OLE/ODBC at the client. See the Internet applications tutorial for more information.
The steps in this tutorial highlight how easy it is to build a Chart from scratch and will introduce you to the Chart Editor to enable you, through later tutorials, to modify and further enhance the appearance and functionality of the Chart. Good Charting !!

Building a Chart

Including TeeChart on a Form

By using TeeChart's installer application you will have succeeded in adding the TeeChart icons to the Toolbox of our programming environment. The TeeChart Chart icon is a representation of a circled (Pie) Chart.

Select the icon in the Toolbar and click and drag out to size TChart on a Form. You will see TChart as a panel with some basic Chart features such as Axis and Title. TeeChart is derived from a panel, you could use the Chart Editor to delete the existing visual features and you would be left with a perfectly servicable 3D panel complete with Border and Bevel properties ! TeeChart is much more than a panel of course, right click on the new TChart and you will see a menu displayed. Select the ActiveX -Edit Chart... option to access the Chart Editor.

For an introduction to TeeChart's other palette components, follow this link to Tutorial 17.

The Chart Editor

The Chart Editor contains access to most commonly used, Chart properties.

To add a new Series mouseclick on the Add.. button and select the Series type from the Series Gallery. If, after selecting a Series type now, you wish to change it later you may do so (with a few exceptions where Series data content may be incompatible) by returning to the first Editor screen and selecting the Change.. button.

The Chart Series Gallery

The Series Gallery now consists of six tabbed pages:

Standard

Standard Series types, those likely to be called upon most frequently.

3D

3D Series types, those that represent 3 dimensional (X, Y, Z) data.

Other

Miscellaneous Series types.

Extended

We have included some example custom Series types.

Financial

Financial Series include more specialised Financial Series types for financial applications.

Stats

Stats Series include more specialised Statistical Series types for planning or mapping applications.

Select a Series type. For this exercise we will choose a Bar Series type. The Gallery will close and the new Series will be displayed in the first Chart Editor screen.

Populate the new data Series

Select the Series tab in the Chart Editor to display the Series configuration properties. The fifth tab on the Series page is the the data source tab.

ADO

If your data source is OLE DB or ODBC compliant then you may map your data directly in the Chart editor.

Select Dataset from the dropdown listbox on the Data Source page and then select the New... button to define the connection source.

Building a new connection string using the default Microsoft OLE DB Provider for ODBC Drivers Provider enables you to select from any of your ODBC data sources with a valid User DSN, including the TeeChart Pro Database.

You may select a table from the available list of tables or write your own SQL query for the data source. SQL queries can be saved as TXT files and brought in as such.

Selecting OK will create a record of the entire connection operation, in this case called DataSet1, and returns you to the to the prior Datasource screen where you may select the columns to add to your Series. To populate our new Bar Series we only require to have Labels and Bar values, where Labels will read on the horizontal (bottom by default) axis and where Bar is the value of the vertical height of the Bar. You may select Close or Apply when you have finished with these fields and you should see the chart already populated with the data from your data source.

Coded data input

For programmed input of data you will need to write some code. This section will show you the steps necessary to build a chart with coded input.

The Series that you previously added with the Chart Editor shows random data at design time. At runtime however, the Series will be empty of data unless you manually populate it. Select a Command button from the Toolbox and place it on your Form. In Visual Basic Double-click on the button to access the code editor (the approach may vary in different programming environments). In the code Editor type these lines:

(Visual Basic)
With TChart1.Series(0)
    .Add 3, "Pears", vbRed
    .Add 4, "Apples", vbBlue
    .Add 2, "Oranges", vbGreen
End With

Run the project and press the command button. Three new bars will appear on your Chart. That's it !! There's no more to it.

The first Series in your Chart has a (0) index, the second (1), etc.. so with multiple series in your Chart you may use the index to select the Series you wish to modify.

The Series' Add method accepts 3 variables, Value, Label and Colour. The Add method thus assumes equal spacing of values on the Label axis (in this case the X-Axis). If your data contains 2 variables you may use the AddXY Method. Add another Command button to your project and put this code in it. Run the Project and add points using this code:

(Visual Basic)
  With TChart1.Series(0)
    If .Count > 0 Then
      'Increment X Axis value and add a new random point
      .AddXY .XValues.Last+(Rnd(100)), (.YValues.Last/.YValues.Last-1)+(Rnd(100)), "", vbBlue
    Else
      'Add a new random point
      .AddXY 1, (Rnd(100)), "", vbBlue
    End If
  End With

Selecting a Series type to suit your needs

The last coded example generated new X and Y values. The X axis distance between points is not constant which will cause overlapping of Bars in some cases, which would be desirable for some but not all applications. Using the Chart Editor to Change the Series type (Enter the Chart Editor at Design time and use the Change button on the first page) to a LineSeries shows an alternative way to graphically represent data with 2 variables. If your data contains more than 2 variables there are other Series Types suited to displaying the data. The following table shows the composition of TeeChart Series types.

Series Type | No. of variables | Datasource Properties
Standard |  |
Gantt | 3 | StartValues, EndValues, AY (Y axis level), AXLabel (Label optionally shown on Y-axis or as mark)
Line | 2 | XValues, YValues, XLabel
Bar | 2 | XValues, YValues (called Bar), XLabel
HorizBar | 2 | XValues, YValues (called Bar), XLabel
Area | 2 | XValues, YValues, XLabel
Point | 2 | Xvalues, YValues, XLabel
Pie | 1 | PieValues, XLabel
Fast Line | 2 | XValues, YValues, XLabel
HorizLine | 2 | XValues, YValues, YLabel
HorizArea | 2 | XValues, YValues, YLabel
Shape | 4 | X0 (Top), Y0 (Bottom), X1 (Left), Y1 (Right)
Bubble | 3 | XValues, YValues, XLabel, RadiusValues
3D |  |
Surface | 3 | XValues, YValues, XLabel, ZValues
Contour | 3 | XValues, YValues, XLabel, ZValues
Waterfall | 3 | XValues, YValues, XLabel, ZValues
Color Grid | 3 | XValues, YValues, XLabel, ZValues
Vector 3D | 3 | XValues, YValues, XLabel, ZValues
Tower | 3 | XValues, YValues, XLabel, ZValues
Iso-Surface | 3 | XValues, YValues, XLabel, ZValues
Point3D | 3 | XValues, YValues, XLabel, ZValues
Bubble | 5 | XValues, YValues, XLabel, RadiusValues, ZValues
Triangle Surf. | 3 | XValues, YValues, XLabel, ZValues
Polar Grid | 3 | XValues, YValues, XLabel, (Polar Grid has Sectors, Tracks and Values)
Extended |  |
Arrow | 4 | StartXValues, StartYValues, XLabel, EndXValues, EndYValues
Polar | 2 | XValues, YValues, Labels (Polar has Angle and Radius)
Radar | 2 | XValues, YValues, Labels (Radar has Angle and Radius)
Polar Bar | 3 | XValues, YValues, Labels (Polar has Angle and Radius)
Bezier | 2 | XValues, YValues, XLabel
Donut | 2 | Angle, YValues, Labels
Smith | 2 | Resistance, Reactance, Labels
Pyramid | 2 | XValues, YValues, XLabels
Map | 3 | XValues, YValues, Polygons, Labels
Org Chart | 2 | XValues, YValues, Labels
Tree Map | 2 | XValues, YValues, Labels
Financial |  |
Point & Figure | 5 | OpenValues, CloseValues, HighValues, LowValues, DateValues
Candle | 5 | OpenValues, CloseValues, HighValues, LowValues, DateValues
Volume | 2 | XValues, YValues (VolumeValues), XLabel
Darvas | 5 | OpenValues, CloseValues, HighValues, LowValues, DateValues
Renko | 2 | XValues, YValues, Labels
Kagi | 2 | XValues, YValues, Labels
Stats |  |
Histogram | 2 | XValues, YValues, XLabel
Horizontal Histogram | 2 | XValues, YValues, XLabel
Error Bar | 3 | XValues, YValues, XLabel, ErrorValues
Error | 3 | XValues, YValues, XLabel, StdErrorValues
High-Low | 3 | XValues, YValues, LowValues, XLabel
BoxPlot | 2 | XValues, SamplesValues, Label
Horizontal BoxPlot | 2 | XValues, SamplesValues, Label
Volume Pipe | 3 | XValues, YValues, Labels
Funnel | 3 | XValues, QuoteValues, OpportunityValues, XLabel
HighLow Line | 3 | XValues, HighValues, LowValues, Labels
Ternary | 5 | XValues, YValues, ZValues, RadiusValues, WeightingValues, Labels
Error Point | 6 | XValues, YValues, LeftError, RightError, TopError, BottomError, Labels
Error Point 3D | 9 | XValues, YValues, ZValues, LeftError, RightError, TopError, BottomError, FrontError, BackError, Labels
Other |  |
Line Point | 2 | XValues, YValues, XLabel
Bar Join | 2 | XValues, YValues, XLabel
Bar 3D | 3 | XValues, YValues, YStartPoint, XLabel
Big Candle | 5 | OpenValues, CloseValues, HighValues, LowValues, DateValues
Image Bar | 2 | XValues, YValues, XLabel
ImagePoint | 2 | XValues, YValues, XLabel
DeltaPoint | 2 | XValues, YValues, XLabel
Wind Rose | 2 | Angle, YValues, Labels
Clock | 2 | Angle, YValues, Labels
Rose | 3 | Angle, YValues, Angle Values, Labels
Calender | 2 | XValues, YValues, Labels
Tag Cloud | 2 | YValues, ZValues, Labels
Gauges |  |
Gauge | 1 | YValue
Numerical Gauge | 1 | YValue
Linear Gauge | 1 | YValue
Vertical | 1 | YValue
Circular gauge | 1 | YValue
Knob Gauge | 1 | YValue

© 1998- Steema Software SL. All rights reserved.


Tutorial 2 - Chart display properties

Chart display features are those which affect the overall appearance of the Chart. They include those properties and methods that define the colour of the Chart background, Titles and their position, margins, borders and bevels, background images, frame and axis visible, pen colours and widths, 3D, walls, etc.

Nearly all these properties are available via the Chart Editor at design or runtime and you may modify these properties programmatically at runtime.

The overall Chart appearance characteristics are grouped into these categories:

General
Axis
Titles
Legend
Panel
Paging
Walls
3D

These are the groupings you will find if you open the Chart Editor and browse the Chart pages. Other properties affect the 'look' of your Chart. These include Series colours and mark characteristics, individual Axis and Grid display properties and labelling. These will be dealt with in later tutorials dedicated to the specialist role of these features.

The Visual Basic demo that accompanies this tutorial is called DisplayProject.vbp and can be found in the "Examples\Visual Basic\Visual Basic 5 & 6\Chart display" folder below your TeeChart installation folder.

Getting started with Chart display properties

Add a new Chart to a Form and you will see it displays in 3D with a grey panel background, 2 walls (Bottom and Left), Frame (which defines the Frame of the Chart's plottable area) and a default Chart Title Header "TeeChart".

Right click on the chart and select 'ActiveX -Edit Chart...' from the menu to access the Chart Editor. The first page is the Series page which is empty and doesn't interest us for this tutorial. Select the second Chart tab 'General' to access the General Chart properties page.

General Chart properties

General options include Mouse, Zoom, Scroll , Cursor, Fonts and Palette.

Moving the cursor over these tabs in the figure above will reveal the corresponding screenshot for each tab in the General group. Here we will only deal with Mouse, Cursor, Fonts and Palette.
Zoom, and Scroll are dealt with in a later tutorial

Mouse
Here you can choose which action (Zoom, Scroll axis or Nothing) you would like to associate to the different mouse buttons and the scroll axis direction if scrolling is set for the mouse wheel.

Cursor
You can select the cursor of your choice from the drop-down list or leave it as the default.

Fonts
Any Text displayed on the Chart can be easily modified by altering the Font properties found under the Fonts tab.

Palette
You can change the colour scheme of the chart by selecting from the many palettes available in the colour palette list.

Axis Properties

Control of the axes is quite a specialised area at its greatest level of intricacy and is dealt with in greater depth in a later tutorial. Here we will cover the fundamentals of Axis and Frame display.

The Axis pages of the editor hold the properties for defining axis and frame characteristics. When opening the Axis tab, the editor shows the Scales options available as seen in the sceenshot below. Moving the cursor over the Minimum, Maximum and Increment tabs reveals the corresponding properties for each.

There are 6 axes in the Chart. Left, Top, Right, Bottom and Depth Right and Depth Top. The Chart Frame displays as a surround to the Chart's plottable area and has no data corresponding features (See BackWall). The Depth axes initialise by default as not Visible. All other Axes are visible from the moment that a Series is added to the Chart and associated with those Axes (Left and Bottom as default). Custom Axes may be added/removed by using the + and - keys on the dialogue. For a Custom Axis to be visible (as for any other Axis) a Series must be associated with the Axis. See the Axis tutorial for more about Custom axes.

The key properties to enable display of axes and frame are:

Visible
This checkbox enables or disables display of all axes. If the Back wall Frame is visible then the Chart surround is still visible when the axes are hidden. The result will be the appearance of a larger Chart as no area is reserved for the axis labels. The Visible property for each Axis (Scales tab) overrides the visible characteristic for each Axis. If you select the Depth Axis in the List then you will note that Depth Axis Scales.Visible is by default 'not visible'.

Runtime

TChart1.Axis.Visible = True

Axis: Left, Right, Top, Bottom and Depth Right and Depth Top Visible
Select the Axis that you wish to display or hide in the Listbox and toggle the Visible checkbox on the Scales tab to control the display for that specific axis.

Runtime

e.g.

TChart1.Axis.Bottom.Visible = False

Titles Properties

The Titles page of the Chart Editor controls the characteristics of the Chart Titles, Header and Footer.

Text
Use the dropdown Combobox to select either Title (Header), SubTitle, Foot or SubFoot. Enter the required text in the Textbox. You may type multiline titles.

Runtime:

The Text property of ITitles is an OLE Strings component. You may add several lines to the Header:

e.g.

With TChart.Header.Text
  .Add("My First Line")
  .Add("My Second Line")
End with

You may then modify lines of text:

e.g.

With TChart1.Header
    .Text(0) = "my1stline revised"
End With

Style Alignment
Alignment refers to the Header (or Footer) alignment with respect to the Chart area NOT the overall Chart Panel. The Chart area is the plottable area of the Chart plus Axis Labels and Legend.

Runtime:

TChart1.Header.Alignment = taCenter

Position
Use Position to override the Title or Footer default position and set a custom position (pixels relation to Chart Top, Left).

Runtime:

TChart1.Header.CustomPosition = True
TChart1.Header.Top = TChart1.Header.Top + 30

Format
Contains the settings for the Title box, e.g. Frame, Background colour, etc.

E.g. Pattern
Pattern refers to the background pattern of the Title or Footer box.

The default is Clear. The selected Pattern will sit behind the Text.

Runtime:

e.g.

TChart1.Header.Transparent = False
TChart1.Header.Brush.Style = bsFDiagonal

Text
Contains the Title Text appearance formatting characteristics.

E.g. Font
The Font button will grant access to the Font Dialog window which allows selection of Windows Fonts and definition of style (italic, bold, etc.) and colour.

Runtime:

TChart1.Footer.Font.Name = "Verdana"
TChart1.Footer.Font.Bold = True

Outline
Outline refers to the Frame for text of the Header or Footer. By default it is set to Visible off. The Outline options derive from IPen.

Gradient
Enable/disable a Background Gradient in the Title box and select its direction and colours.

Shadow
Properties for display of the Header or Footer box Shadow. You may define colour and size.

Runtime:

TChart1.Header.Transparent = False
TChart1.Header.ShadowColor = vbCyan

Legend Properties

Legend contents are a specialist subject that will be dealt with in a later tutorial. In the Legend page of the Chart Editor you may define appearance aspects of the Legend. Important initial steps are to control Legend alignment and visible properties, colour, font, frame, shadow, etc..

Style
Toggle On/Off Legend display and set Legend display content characteristics (inclusion of Checkboxes, etc).

Runtime:

Example using Checkbox to control Legend display.

  With TChart1.Legend
    If Check11.Value = 1 Then
      .Visible = True
    Else
      .Visible = False
    End If
  End With

Dividing Lines
Used to draw lines within the Legend box between the Legend entries. IPen properties apply.

Runtime:

TChart1.Legend.DividingLines.Visible = True
TChart1.Legend.DividingLines.Color = vbBlue

Position
Sets the default display position or enables custom positioning of the Legend. TChart will change the shape of the Legend to fit the location. If the Legend is set to the side (left or right) of the Chart the contents of the Legend, by default, sit as a list from top to bottom. If the Legend sits below or above the Chart then the Legend contents are placed side by side. The default behaviour may be overridden by using the Resize Chart option and/or by using Custom positioning. See the Legend tutorial for more about custom positioning of the Legend.

E.g. ResizeChart
Resize Chart defines whether or not the Chart will leave space for the Legend when it paints. This allows the Legend to be placed within the Chart area.

Runtime:

TChart1.Legend.ResizeChart = True

%Top position
Defines the Legend box displacement from the top of the Chart Panel.

Runtime:

TChart1.Legend.TopPos = 20

Symbols
Size and formatting of the Legend symbols.

%Color Width
Defines the width of the colour boxes within the Legend.

Runtime:

TChart1.Legend.ColorWidth = 50

Format
Contains the settings for the Legend box, e.g. Fill Colour, Frame colour, style and width, Pattern style, colour and image, bevel style and size and checkboxes for Round Frame and Transparent.

Text
Text characteristics for the Legend text contents.

Runtime

With TChart1.Legend
   .Color = vbBlue
   .Font.Name = "Times New Roman"
   .Font.Color = vbYellow
End With

Gradient
Enable/disable a Background Gradient in the Legend box and select its direction and colours.

Shadow
Properties for display of the Legend box Shadow. You may define colour and size.

Runtime:

TChart1.Legend.ShadowColor = vbCyan
TChart1.Legend.ShadowSize = 4

Panel Properties

The TeeChart Panel page allows you to set parameters which radically enhance the appearance of the Chart. Panel Gradient effects are best seen by monitors that support true colour but some colour combinations on 255 colour screens are very acceptable.

By now you are familiar with TeeChart properties so we won't run through all the properties here. Panel properties and methods may be accessed via the Panel interface:

Select TChart1.Panel to see a list and example of all the properties. The Visual Basic demo that accompanies this tutorial has comprehensive examples of panel properties.

Key areas are:

Color
E.g. Panel Color
Panel colour will paint the whole Chart background with the chosen colour. However, if you select to view a background Gradient or BackImage they will hide the Panel colour. If you set a Back colour it will replace the Panel colour within the Chart Frame only.

Border
You may define Border independently or in conjunction with the Bevel properties. With Border set to Visible True you will obtain a 'sunken' border effect on the outside of the Chart Panel. Mixing Bevel and Border and manipulating Width gives almost any combination of 3D effects.

E.g. Bevel Inner/Bevel Outer/Width
These properties will produce a variety of 3D effects on the Border of the Chart panel. Modify them at design time to see how they affect the Chart border bevels.

Margins

Margins are defined as the distance between the Chart Border and the Chart Frame and can be expressed as either a percentage of the overall dimensions of the Chart Panel or as absolute pixel values.

Moving the spin boxes in the Chart Editor Margins box will show you at design time the effect of changing each Margin.

Runtime properties are:

TChart1.Panel.MarginTop
TChart1.Panel.MarginLeft
TChart1.Panel.MarginRight
TChart1.Panel.MarginBottom

The example applied in the demo project uses a Horizontal Scrollbar:

Private Sub Hscroll3_Change()
  TChart1.Panel.MarginLeft = Hscroll3.Value
End Sub

Gradient
To define a Gradient you must select a StartColor and EndColor (plus, optionally MidColor) and enable as Visible the Gradient. The Gradient will cover the whole Chart panel. Gradient direction defines the direction of colour change between Start, Mid and EndColor.

Runtime:

With TChart1.Panel
    .Gradient.Visible = True
    .Gradient.StartColor = vbRed
    .Gradient.MidColor = vbWhite
    .Gradient.EndColor = vbBlue
    .Gradient.Direction = gdFromTopLeft
End With

E.g. BackImage
You may select any bitmap (.bmp) file as BackImage. The BackImage may be centered, tiled or stretched on the Chart Panel, or may be restricted to the Chart Frame boundaries.

Runtime:

Use Panel.BackImageLoad to add a BackImage to a Chart at runtime.

TChart1.Panel.BackImageLoad "C:\...\myfile.emf"

Paging Properties

TeeChart paging allows a Chart to be divided into a set number of points per page and for the Chart to be leafed through. See the Paging tutorial for more information.

Walls Properties

This page in the Chart section of the Chart Editor applies properties to the Chart Walls. There are 4 Walls: Left, Right, Bottom and Back, that may be represented in 2D or 3D.

Wall properties are accessible via the TChart1.Walls property.

Wall Border
The Border button takes you to the Pen definition for the IWalls interface. This is the same Pen available for many other TeeChart objects.

The visible property enables/disables display of the Border. In the case of the BackWall, where axes are Visible the Wall Border will be hidden behind those axes so you will only see the result of enabling/disabling the Border if you hide some or all axes (e.g. Make axes Top and Right invisible to see the result of changing the colour of Wall Border i.e. TChart1.Walls.Back.Pen.Color = vbCyan).

See ChartPen for other characteristics of the Border Pen. You can change these properties at design time.

3D

3D is extremely flexible in TeeChart Pro version 5. You now have the option to display the Chart as:

2D | Flat Chart, viewed from front
3D Orthogonal | 3D represented by vectored Lines to indicate depth
3D Native Windows | 3D using 3D Canvas with 180º Chart rotation
3D Open GL | 3D using Open GL Canvas with 360º Chart rotation

Editor options:

3 Dimensions
Selecting this property (toggling) will change the Chart from a 3D to a 2D Chart in design time and the setting will take effect for runtime.

3D %
Controls the depth of the 3D effect. Changing the value of this property will show you at design time the effect of changing the 3D percentage.

Runtime equivalent properties are:

3D visible

TChart1.Aspect.View3D

3D%

TChart1.Aspect.Chart3DPercent

An applied example of these properties uses a CheckBox and Horizontal ScrollBar:

Private Sub Check5_Click()
  With TChart1
    If Check5.Value = 1 Then
      .View3D = True
      HScroll1.Enabled = True
    Else
      .View3D = False
      HScroll1.Enabled = False
    End If
  End With
End Sub

Private Sub HScroll1_Change()
  TChart1.Chart3DPercent = HScroll1.Value
  Label8.Caption = Str$(HScroll1.Value)
End Sub

The Orthogonal Option, when disabled, enables Windows Native 3D mode allowing you to Rotate, Elevate and offset the Chart. The Zoom option allows you to bring forward or move away the whole Chart. Zoom internally in the Chart on Data Series is still available at runtime.

The Perspective property allows you to set a distance perspective as if looking into a room. Perpsective offers a visual enhancement for Charts used for presentation purposes.

For a further reference on 3D options take a look at Tutorial 16, Chart 3D and OpenGL.


Tutorial 3 - Chart Paging

If the data source for your Chart contains more data than can legibly displayed on one Chart screen you may wish to divide the Chart into pages that can be leafed through. This can be achieved via the Chart Editor or programmatically.

See the VB6 Paging demo for a working example of this tutorial, "Examples\Visual Basic\Visual Basic 6\Paging\PageProject1.vbp".

Contents
Paging with the Chart Editor
Paging with the ChartPageNavigator component
Paging by code
Print-previewing a multipage Chart

Paging with the Chart Editor

Page sizes may be defined with the Chart Editor. It will still be necessary to add paging buttons or the ChartPageNavigator component to your project or you could make the Chart Editor available at runtime to allow users to change pages with the Editor.

At design time, select the Paging page in the Chart Editor.

In the Points per Page: box, type (or scroll to) the number of Series points you wish to see on the Chart page. If you're coding the data values for the Series, the navigation buttons will not be highlighted until you run the project, populate the Series and show the Chart Editor at runtime. If you are connected to an ODBC datasource you should see paging take effect immediately at design time.

Runtime:

To access paging properties via the chart editor at runtime use ShowEditor.

e.g.

TChart1.ShowEditor

Paging with the ChartPageNavigator component

The ChartPageNavigator component offers easy intuitive Chart page navigation, similar to existing navigators for database recordsets.

Set the Navigator's Chart property to the TeeChart you wish to Page.

e.g.

ChartPageNavigator1.Chart = TChart1

Paging by code

Paging properties and methods are available via the IPage interface.

Steps required to add paging to your Chart:

  1. Define Points per page

    2. Use MaxPointsPerPage to define the number of points to display on each page.

    e.g.

    TChart1.Page.MaxPointsPerPage = 10

  2. Add Navigation buttons to the Chart's Form (if not using the ChartPageNavigator).

    3. Example:

    First Page

    TChart1.Page.Current = 0

    Advance a page

    TChart1.Page.Next

    Goto previous page

    TChart1.Page.Previous

    Last Page

    With TChart1
  .Page.Current = .Page.Count
End With
  3. Decide what to do with the last page.

    4. The last page is unlikely to have exactly the correct number of points to match the point quantity in the other Chart pages. You may choose to Scale the Last page which will 'best fit' the remaining points to the page, adjusting the axis scale accordingly, or you may treat the page as previous pages with the same number of points which may leave the last page rather empty if there are not many points for the page.

    TChart1.Page.ScaleLastPage = False   (default = True)

  4. Show the user a page number

    5. The TChart OnPageChange event may be used to show the user the existing page number. Here using a Label to the Page number:

    Label4.Caption = Str$(TChart1.Page.Current) + " of " + Str$(TChart1.Page.Count)

Print-previewing a multipage Chart

Multipage Charts may be print previewed whilst being navigated. Simply set the Previewer's Chart property to the Chart which you wish to view then use the ChartPageNavigator component to page the Chart.

That's all for this tutorial ! The next tutorial deals with advanced Axis and Legend manipulation.


Tutorial 4 - Axis Control

TeeChart Pro will automatically define all Axis labelling for you and offers plenty of flexibility to tailor any specific requirements you may have. TeeChart Pro offers true Multiple Axes. These are available at design or run time and offer countless possibilities and flexibility for Axis definition. See the section in this tutorial for more information.

Contents

Axes control - Key areas

Scales
Increment
Titles
Labels
Ticks
Axis position

Additional Axes

Copying axes
Multiple axes

Axis events

OnClickAxis
OnGetAxisLabel
OnGetNextAxisLabel

Axes control - Key areas

Scales

Axis scales are set automatically when you add Series data to your Chart. You may change from the defaults at design time or at runtime by using Axis properties.

Non date-time data
When adding a new Series, the Scales section of the Axis Page of the Chart Editor will show Automatic selected and other options greyed out. All values shown are numeric.
Date-time data
When a Series has datetime set to true (for that axis) on the Series, General page, the Scales section of the Axis Page of the Chart Editor will show Automatic selected and other options greyed out. Values are shown with Date-time values.

Automatic selects the best axis scale range to fit your data. If you turn Automatic off the scales section will ungrey options and you can change Axis values. Important, remember to select the Axis that you wish to configure from the list of Axes on the left of the page.

Add a Line Series to a Chart add a Command Button with the following code:

Dim t As Integer
For t = 0 To 40
  With TChart1.Series(0)
    .Add CInt((Rnd) * t), "", vbRed
  End With
Next t

Running the code in the button will draw a Line Series with 40 random values. Go to the Chart Editor at design time. Turn Automatic 'off' in the Bottom Axis scales section of the Axis page. You may now configure Maximum and minimum values for the Axis scale. Running the code again will show values depending on the values you configured for the Axis. Using the right button of of the mouse you may scroll to see the remaining values.

Setting axis scales by code
You can change the Maximum and Minimum at runtime using this code:

With TChart1.Axis.Bottom
  .Automatic = False
  .Maximum = 36
  .Minimum = 5
End With

You may set Axis scale Maximum and Minimum to automatic individually. e.g:

With TChart1.Axis.Bottom
  .AutomaticMaximum = True
  .AutomaticMinimum = False
  .Minimum = 5
End With

Offset
You may set Axes to have Offsets (in pixels) for both Minimum and Maximum scales.

TChart1.Axis.Left.MaximumOffset = 4
TChart1.Axis.Left.MinimumOffset = 4

Increment

You may tailor the intervals for the Axis. Select the Desired Increment combobox from the Scales section of the Axis page and add the increment you require. You may change this by code at runtime:

With TChart1.Axis.Bottom
  .Increment = 20
End With

Datetime data

If your data is datetime (You may set the data to datetime for your Series by going to the Series, General page), the Chart, Axis page, scales section will show datetime range. Select the increment from the range shown in the Desired Increment combobox.
add some sample data

For t = 1 To 25
   With TChart1.Series(0)
       .AddXY DateValue("2017, 11, " & t), Rnd(t) * t, "", vbRed
   End With
Next t

Change the Increment at runtime:

With TChart1.Axis.Bottom
  .Increment = TChart1.GetDateTimeStep(dtTwoDays)
End With

See the Axis.ExactDateTime property for more information about date axis labelling

Note

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the LabelsSeparation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate 'best fit'. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels section and LabelsAngle property.

Titles

Titles are set in the Titles section of the Axis page. You may change the Title text for the Axis and its font. The angle may be selected from values 0, 90, 180, 270 degrees. For runtime see Axis Title Class.

Labels

See the AxisLabels Class (IAxislabels interface) for a resume of Labels properties.

Note

When changing axis label frequency, bear in mind that TeeChart will avoid label overlap according to the setting of the Labels.separation property. This means that if the label frequency is too high for the labels to fit, then TeeChart will allocate 'best fit'. Changing the label angle and label separation are 2 options that may help you fit the labels you require. See the Labels.Angle property.

Label formats
You may apply all standard number and date formats to Axis labels. The Axis page, Labels section contains the field "Values format". If your data is datetime the field name changes to "Date time format". In the Editor drag the help "?" icon onto the field to get a full listing of options. At runtime use:

With TChart1.Axis.Bottom
  .Labels.ValueFormat = "#,##0.00;(#,##0.00)"
End With

'or for datetime data

With TChart1.Axis.Bottom
  .Labels.DateTimeFormat = "dd/mmm/yy" 'Datetime
End With

MultiLine labels
Axis labels can be displayed as multi-line text instead of a single line of text. Lines are separated using the carriage-return ascii character ( #13 ).

Example
//Add the Series labels in this way and apply 'Marks' as Axis labelling style
  TChart1.Series(0).Add 1234, "New"+chr$(13)+"cars", vbRed
  TChart1.Series(0).Add 2000, "Old"+chr$(13)+"bicycles", vbBlue
Example for DateTime labels:

The following will show the Bottom Axis labels in two lines of text, one showing the month and day, and the second line showing the year:
Feb-28 Mar-1 .. 1999 1999 ..

TChart1.Series(0).AddXY DateValue("28,2,1999"), 100, "", clTeeColor
TChart1.Series(0).AddXY DateValue("1,3,1999"), 200, "", clTeeColor
TChart1.Series(0).AddXY DateValue("2,3,1999"), 150, "", clTeeColor
TChart1.Series(0).XValues.DateTime = True
TChart1.Axis.Bottom.Labels.DateTimeFormat = "mm/dd hh:mm" 'space

If you set the Labels.MultiLine property to True, the axis will automatically split labels in lines where it finds a space.

TChart1.Axis.Bottom.Labels.MultiLine = True

Dividing the Label into two:

'mm/dd' for the first line
'hh:mm' for the second line

At run-time you can always split the label into lines programatically, using the OnGetAxisLabel event:
Private Sub TChart1_OnAfterDraw()
  TChart1.Axis.Left.Labels.TeeSplitInLines LabelText, " "
End Sub

The global "TeeSplitInLines" procedure converts all spaces in "LabelText" to line separators (returns).

The axis Labels.Angle property ( label rotation in degree angles 0, 90, 180 or 270 ), can also be used with multi-line axis labels.

Customising Axis labels
Further Label control may be obtained by using Axis events. The events permit you to activate/deactivate/change any individual Axis label. The following example modifies each Label, putting a textual phrase in front of the point index value.

'set LabelStyle to 'Mark' with the TChart editor or use:-
TChart1.Axis.Bottom.Labels.Style = talMark

'OnGetaxisLabel event
Private Sub TChart1_OnGetAxisLabel(ByVal aAxis As Long, ByVal SeriesIndex As Long, ByVal ValueIndex As Long, LabelText As String)
 If aAxis = atBottom Then
   LabelText = "Period " + Str(ValueIndex)
 End If
End Sub

See the section entitled Axis events for more information about customising labels with Axis events.

Axes labels may be modified at specific positions with custom text and formatting without the need to use TeeChart events, making them much easier to modify serverside in ASP scenarios.

Private Sub Form_Load()
Dim v As Variant
  v = Array(200, 0, 123, 300, 260, -100, 650, 400)
  TChart1.AddSeries scLine
  TChart1.Series(0).AddArray 8, v
  AddCustomLabels
End Sub

Private Sub AddCustomLabels()
  TChart1.Axis.Left.Labels.Clear
  TChart1.Axis.Left.Labels.Add 123, "Hello"
  TChart1.Axis.Left.Labels.Item(0).Font.Size = 16

  TChart1.Axis.Left.Labels.Add 466, "Good" & Chr(13) & "Bye"
  TChart1.Axis.Left.Labels.Item(1).Transparent = False

  TChart1.Axis.Left.Labels.Add 300, ""

  TChart1.Axis.Left.Labels.Add -100, ""
  With TChart1.Axis.Left.Labels.Item(3)
    .Transparent = False
    .Transparency = 50
    .Color = vbBlue
  End With
End Sub

Logarithmic Labels
Normal Logarithmic labelling may be set in the following way:

With TChart1.Axis.Left
 .Logarithmic = True
 .Increment = 0 ' the default
 .SetMinMax 0, 10000
 .Labels.ValueFormat = "#e+0" ' exponential format
End With

Labels will be set according to the Logarithmic base (default 10) thus, in this case giving labels at 1,10,100,1000,10000.

Ticks and Minor

There are 3 tick types and 2 types of Grid. You may change the length, width and colour of each tick and Grid type. Changes can be made to Ticks, their associated Grid and Inner Ticks via the «Ticks» tab; changes to Minor Ticks and their associated Grid can be made via the «Minor» tab.

With TChart1.Axis.Bottom
  .TickLength = 7
  .Ticks.Color = vbGreen
  .MinorTickCount = 10 'change number of minorticks between (major) Ticks
End With

Axis position

Axes have a property to modify where each axis is to be located. In this example, the axis is moved 50% of the total Chart width, so it is shown at the chart center:

TChart1.Axis.Left.PositionPercent = 50

Additional Axes

Copying axes

TeeChart offers 5 axes to be associated with data Series, Left, Top, Bottom, Right and Depth. When you add a new series to a Chart you may define to which of the axes the Series should be related (Go to the Series tab, General page). You may repeat anyone (or all) of the front 4 axes at any place on the Chart by using the Axis Customdraw method. Note that this method makes a copy of your Axis, it does not add a new Custom Axis. See the next section, Multiple Custom Axes, for more information.

Example:

'fill the Series for this example with random data
Private Sub Command1_Click()
Dim t As Integer
  For t = 0 To 20
    TChart1.Series(0).AddXY t, ((100 * Rnd) + 1) - ((Rnd * 70) + 1), "", vbRed
  Next t
End Sub

'Put this code in the TChart1_OnBeforeDrawSeries() event:
Dim posaxis As Integer
  With TChart1
   If .Axis.Left.Maximum > 0 Then
    'When scrolling or on zoom always keep the gridlines enclosed in the Chart rectangle
    .Canvas.ClipRectangle .Canvas.Left, .Canvas.Top, (.Canvas.Left + .Canvas.Width), _
                          (.Canvas.Top + .Canvas.Height)
    'Always draw the 2nd vertical Axis at the middle point of the Chart
    posaxis = (.Canvas.Left) + (.Canvas.Width * 0.5)
    .Axis.Left.CustomDraw posaxis - 10, posaxis - 20, posaxis, True
    'Draw the 2nd Horizontal axis at the level of "10" on the vertical axis
    posaxis = (.Axis.Left.CalcYPosValue(10))
    .Axis.Bottom.CustomDraw posaxis + 10, posaxis + 40, posaxis, True
    .Canvas.UnClipRectangle
   End If
  End With
Custom axes

In this example, TeeChart will plot the New axes, one horizontal and one vertical in the centre of your Chart. When you scroll the Chart (dragging with right mouse button), the new vertical axis will always remain central to the Chart, the new horizontal axis will move up and down with vertical scrolling. The new axes are exact copies of the default axes.

Multiple Custom Axes

Together with the PositionPercent and stretching properties, it’s possible to have unlimited axes floating anywhere on the chart. Scroll, zoom, and axis hit-detection also apply to custom-created axes. Creating extra axes is now possible both at designtime via the Chart Editor and at runtime via a few lines of code:

Via the Chart Editor

TeeChart offers you the ability to create custom axes at designtime enabling them to be saved in TeeChart's tee file format. To achieve this, open the Chart Editor and click on the Axis tab and then select the "+" button to add a Custom Axis. Then select the Position tab making sure you have your new Custom Axis highlighted. The Horizontal checkbox on this page allows you to define your new Custom Axis as an horizontal axis or to leave it as the default vertical axis. The rest of this page and the other tabs in the Axis page can be used to change the Scales, Increment, Titles, Labels, Ticks, Minor Ticks and Position of the Custom Axis as explained above. To associate this new Custom Axis with the Data Series you desire select the Series tab and go to the General page where the dropdown Comboboxes 'Horizontal Axis' and 'Vertical Axis' will enable you to select your new Custom Axis depending on whether you previously defined it as vertical or horizontal.

Via Code

Example
Private Sub Command1_Click()
TChart1.Series(0).VerticalAxisCustom = TChart1.Axis.AddCustom(False)
'You can modify any property of the new created axes, such as the axis color or axis title
With TChart1.Axis.Custom(0)
    .AxisPen.Color = vbGreen
    .Title.Caption = "Extra axis"
    .Title.Font.Bold = True
    .Title.Angle = 90
    .PositionPercent = 50 'percentage of Chart rectangle
End With
End Sub

You are able to then position the new Axis in overall relation to the Chart by using the StartPosition and EndPosition properties.

StartPosition=50
EndPosition=100

These figures are expressed as percentages of the Chart Rectangle with 0 (zero) (in the case of a vertical Axis) being Top. These properties can be applied to the Standard Axes to create completely partitioned 'SubCharts' within the Chart.

Example
With TChart1.Axis.Left
    .StartPosition = 0
    .EndPosition = 50
    .Title.Caption = "1st Left Axis"
    .Title.Font.Bold = True
End With

The above 2 coded examples when combined with the following data:

For t = 0 To 10
    TChart1.Series(0).AddXY t, 10 + t, "", clTeeColor
    If t > 1 Then
      TChart1.Series(1).AddXY t, t / 2, "", clTeeColor
    End If
Next t

...will show the following Chart:

Multiple axes

Options are limitless! We advise caution when using Custom Axes as it is easy to start filling the screen with new axes and to lose track of which one you wish to manage !

Axis events

Axis events offer runtime flexibility to modify Axis Labels and present user interactivity on Axis Clicks.

OnClickAxis

See the OnClickAxis event.

Example

Private Sub TChart1_OnClickAxis(ByVal Axis As Long, ByVal Button As TeeChart.EMouseButton, ByVal Shift As TeeChart.EShiftState, ByVal X As Long, ByVal Y As Long)
'Shows Axis point clicked when click on Bottom Axis.
If Axis = atBottom Then
  MsgBox "Clicked Bottom Axis at " & TChart1.Axis.Bottom.CalcPosPoint(X)
End If
End Sub

OnGetAxisLabel

Can be used to modify Axis Labels. See the OnGetAxisLabel event.

Example

Private Sub TChart1_OnGetAxisLabel(ByVal aAxis As Long, ByVal SeriesIndex As Long, ByVal ValueIndex As Long, LabelText As String)
'Add following text to Bottom Axis Labels
If aAxis = atBottom Then
  LabelText = "Period " + LabelText
End If
End Sub

OnGetNextAxisLabel

Can be used to decide which Axis Labels should be displayed. See the OnGetNextAxisLabel event. You should use the MoreLabels Boolean property to include/exclude Axis Labels.

Example

Private Sub TChart1_OnGetNextAxisLabel(ByVal Axis As Long, ByVal LabelIndex As Long, LabelValue As Double, MoreLabels As Boolean)
If Axis = atBottom Then
   MoreLabels = True
   'Only label if following cases are true
   Select Case LabelIndex
      Case 0: LabelValue = 11
      Case 1: LabelValue = 19
      Case 2: LabelValue = 23
      Case Else: MoreLabels = False
   End Select
End If
End Sub


Tutorial 5 - Legend design

See the coded example, Legend control, in the Visual Basic 5 & 6 demos folder for a working example of some of the techniques outlined in this Tutorial.

Contents

Legend control

Style Tab
Position Tab
Symbols Tab
Title Tab
Format Tab
Border Tab
Text Tab
Gradient Tab
Shadow Tab
Emboss Tab
Picture Tab

Customising Legends

OnGetLegendRect event
OnGetLegendPos event
OnGetLegendText event

Legend control

Legend parameters are accessible via the Chart Editor, Chart tab, Legend page.

Legend parameters. See Legend class help for more information

Style Tab

Legend Style
Legend default Style "Automatic" will put Series point values in the Legend when there is only one Series in the Chart. When the Chart contains more than one Series, "automatic" will put Series names in the Legend. In the Editor use the Dropdown Combobox to obtain values other than the default. If you change the Legend Style to display values and there are more than one Series in your Chart, TeeChart Pro will display the values of the first Series. You may modify the display using custom options. See Customising Legends

TChart1.Legend.LegendStyle = lsLastValues
'Puts the last value of each Series in the Legend box

Text Style
See the TextStyle property for a list of possible Legend text styles.

Vertical Spacing
Allows you to modify the spacing between Legend entries.

Dividing Lines
The Dividing Lines button gives access to a Border Editor window where you can make the lines between Legend entries Visible and change their Color, Style and Width.

Visible
This Visible checkbox enables/disables the display of the entire Legend.

Inverted
Inverting the Legend reverses the order of the Legend entries.

Check Boxes
Changes the Legend Style to "Series Names" and displays a check box next to each series allowing it to be made invisible or visible.

Font Series Color
Changes the color of the font of the Legend text to the series color.

Position Tab

Position
There are 4 positions available using the Alignment property, Top, Bottom, Left and Right. Right is the default position. The default positioning of the Legend will always be outside the Chart. See the section about customising Legends for more information about positioning Legends.

Resize Chart
The Resize Chart property, when not enabled, will draw the legend within the Chart frame area. Whilst this may be satisfactory for some Legend positioning requirements, better control of Legend positioning in relation to the Chart frame can be achieved by using the Legend Margin property.

Margin
Changing the Margin property value will move the Chart frame in relation to the Legend, NOT vice versa. Thus, making a Margin value negative will move the Chart over the Legend (increasing the size of the Chart rectangle area). However, the properties are not intended for repositioning of the Legend over the Chart, better to use the techniques outlined in Customising Legends.

Position Offset %
0% is defined as a horizontal Legend touching the right Chart canvas border and a vertical Legend touching the top one. Legends are offset relative to these positions.

Custom
This check box will disable the Resize Chart property and will enable you to position the Legend in pixels anywhere on the Chart Canvas.

Symbols Tab

Visible
Use the Visible property to show or hide the color rectangles (symbols).

Width
Set Width property to define the width of the Legend symbols.

Width Units
Use the WidthUnits property to define how the width must be interpreted.

Position
Use the Position property to set the position of the color rectangles.

Continuous
Use Continous property to let the different legend color rectangles flow into each other. When set to True, the color rectangles of the different items are drawn fixed to each other (no vertical spacing). When set to False, the color rectangles are drawn as seperate rectangles.

Squared
Use the squared property to make the legend color rectangles square.

Default border and Border...
Use these properties to override the default border of the legend symbols with your own customised one.

Title Tab

Options
Here you can add the text you wish to use for the Legend Title and align the the text within the Title frame. Use the Visible checkbox to Hide/Unhide the Title.

Format
Use the properties to change the color, pattern and transparency of the Title area background

Border
Mixing Bevel and Frame properties and manipulating Width gives almost any combination of 3D effects. By checking Round Frame and selecting the radius size will give various rounded corners to the Title area.

Text
Use the many properties related to the Title Text to personalize the Font and related effects.

Gradient
Use the Visible property to show or hide the Title area background color gradient. An almost infinite number of gradients can be achieved from combining different gradient styles, colours, directions and sub-gradients.

Shadow
Use the Shadow properties to create a shadow effect for the Title area.

Emboss
Similar to the Shadow properties, you can use the Emboss properties to create a embossed effect for the Title area.

Picture
You can add an image to the Title area background and then modify it in many ways using the different Filters, Style and position properties.

Format Tab

Color
The color property sets the color for the Legend canvas.

Pattern
Sets the pattern for the Legend canvas.

Transparent
Makes the legend canvas transparent leaving just the Legend text and symbols on display.

Transparency
Sets the level of transparency for the legend canvas.

Border Tab

Bevel
Use the Bevel property to define the Legend's bevel.

Frame
Sets Legend Frame properties: Visible, Style, Color and Width.

Size
Sets the size of the Legend's bevel.

Round Frame
Rounds the corners of the Legend Frame.

Text Tab

This page gives access to properties which change the appearance of the Legend text's font, outline, intercharacter spacing and shadow.

Gradient Tab

Use this page to draw a gradient onto the legend canvas and change it's direction and colours.

Shadow Tab

Sets the colour and size of the Legend's shadow.

Emboss Tab

You can add a personalised Embossing effect to the legend canvas by combining the colour, size, transparency and blur properties.

Picture Tab

Adds an image to the Legend canvas which you can then modify in many ways using the different Filters, Style and position properties.

Customising Legends

Legend events offer the option to completely control and define the Legend appearance and content.

OnGetLegendRect event

The Legend outer rectangle, permits changes to the overall size and position of the Legend box. Use in conjunction with OnGetLegendPos to reposition the Chart Legend and contents.

e.g.
Private Sub TChart1_OnGetLegendRect(Left As Long, Top As Long, Right As Long, Bottom As Long)
Left = Left - 100
Right = Right - 100
End Sub

OnGetLegendPos event

Modifies the contents of the Legend. The following example could be used with the code above to move Legend contents to the new Legend rectangle.

Private Sub TChart1_OnGetLegendPos(ByVal Index As Long, X As Long, Y As Long, XColor As Long)
X = X - 100
End Sub

OnGetLegendText event

Modifies the text of the Legend contents.

Private Sub TChart1_OnGetLegendText(ByVal LegendStyle As Long, ByVal ValueIndex As Long, LegendText As String)
LegendText = LegendText + Str$(Index)
End Sub

When placing the Legend within the Chart rectangle area, bear in mind that the Legend paints before Series and Axes and will appear below either of those at any intersection point.


Tutorial 6 - Working with Series

Series Types

Series Class structure
Choosing a Series Type
Adding data to a Series
Deleting data points from a Series
Adding Null points to a Series

Mixing Series Types on a Chart

Adding New Series
Choose Axes for a Series
Connecting Series
Changing Series order

Series Value list

Accessing Series Values
Example using Values

Series events

OnClickSeries
OnGetSeriesPointerStyle
OnGetSeriesMark
OnMouseEnterSeries and OnMouseLeaveSeries

Series Types

The TChart Series class is the common ancestor for all Series types. When using the TeeChart online help or referencing the html help pages via the tutorials, to obtain help on any Series Type, take a look at Series properties and methods on the Series Type's help page where a list of all inherited properties and methods will be included.

Series Class structure

As a little background on the structure of the TeeChart Type Library, here is an explanation of the Series Classes and interfaces. The diagram below shows the relationship between TeeChart Series classes. All classes derive from the generic "Series" class and thus share "Series" properties and methods. Several other generic Classes derive from Series (CustomSeries, CustomBarSeries and CircledSeries), these are highlighted in green and their interfaces are not directly accessible for programming, their characteristics are inherited by their descendant Series types. All derived Series (in red) are accessible in the TeeChart gallery for inclusion in your Chart. TeeChart Series, derived in this way, allow programmable access via a common index structure (see example code later in this section).

TeeChart Pro's internal Series Class hierarchy

The Activex Type Library presents the classes, as interfaces, in a linear form. Thus presenting a homogenous approach to accessing any Series Type specific properties and methods. Common properties and methods are directly accessible in the Series interface.

Shows how TeeChart Pro's Series' interfaces can be accessed.

An example of mixing different series classes in the same Chart would be to add a Area (Series(0)), Bar (Series(1)) and Line (Series(2)) Series to a Chart using the Chart Editor at design time. All access a common index structure, the Chart's Series list. To work with the Series may look something like the below:

'You could add the Series at runtime
With TChart1
  .AddSeries scArea
  .AddSeries scBar
  .AddSeries scLine
End With

With TChart1
  'Use Series common properties
  .Series(0).FillSampleValues 10  '  Put random values in the Area Series
  .Series(1).FillSampleValues 10  '  Put random values in the Bar Series
  .Series(2).FillSampleValues 10  '  Put random values in the Line Series
  .Series(1).Marks.Visible = False '  Bar Series default is Marks 'On', turn them off
  .Series(2).Marks.Visible = True '  Line Series default is Marks 'Off', turn them on
  With TChart1.Series(1).asBar
    'Modify Bar specific properties
    .BarStyle = bsPyramid  ' Change Bar type
    .BarPen.Color = vbCyan ' Bar bounding lines colour
  End With
  With TChart1.Series(2).asLine
    'Modify Line specific properties
    .Stairs = True  '  Set line to Stairs
    .LinePen.Color = vbBlue  ' LineSeries bounding lines colour
  End With
  With TChart1.Series(0).asArea
    'Modify Area specific properties
    .AreaBrush = bsFDiagonal ' Area fill pattern
  End With
End With

Choosing a Series Type

Choosing a Series Type for a Chart will very much depend on your own requirements for the Chart. There are occasions however, when due to the number of variables to plot, the choice of Chart may depend on which Series types support the number of input variables. The following table shows the number of variables allowed by some Series types. For the brevity of this tutorial we haven't included all the possible Series types offered with TeeChart.

Series Type | No. of variables | Datasource Properties
Basic |  |
Gantt | 3 | StartValues, EndValues, AY (Y axis level), AXLabel (Label optionally shown on Y-axis or as mark)
Shape | 4 | X0 (Top), Y0 (Bottom), X1 (Left), Y1 (Right)
Bubble | 3 | XValues, YValues, XLabel, RadiusValues
Line | 2 | XValues, YValues, XLabel
Bar | 2 | XValues, YValues (called Bar), XLabel
HorizBar | 2 | XValues, YValues (called Bar), XLabel
Area | 2 | XValues, YValues, XLabel
Point | 2 | Xvalues, YValues, XLabel
Pie | 1 | PieValues, XLabel
Fast Line | 2 | XValues, YValues, XLabel
HorizLine | 2 | XValues, YValues, YLabel
HorizArea | 2 | XValues, YValues, YLabel
3D |  |
Surface | 3 | XValues, YValues, XLabel, ZValues
Contour | 3 | XValues, YValues, XLabel, ZValues
Waterfall | 3 | XValues, YValues, XLabel, ZValues
Color Grid | 3 | XValues, YValues, XLabel, ZValues
Vector 3D | 3 | XValues, YValues, XLabel, ZValues
Tower | 3 | XValues, YValues, XLabel, ZValues
Point3D | 3 | XValues, YValues, XLabel, ZValues
Triangle Surf. | 3 | XValues, YValues, XLabel, ZValues
Other |  |
Bar 3D | 3 | XValues, YValues, YStartPoint, XLabel
Image Bar | 2 | XValues, YValues, XLabel
Wind Rose | 2 | Angle, YValues, Labels
Clock | 2 | Angle, YValues, Labels
Line Point | 2 | XValues, YValues, XLabel
Bar Join | 2 | XValues, YValues, XLabel
Calender | 2 | XValues, YValues, Labels
Big Candle | 5 | OpenValues, CloseValues, HighValues, LowValues, DateValues
ImagePoint | 2 | XValues, YValues, XLabel
DeltaPoint | 2 | XValues, YValues, XLabel
Extended |  |
Polar | 2 | XValues, YValues, Labels (Polar has Angle and Radius)
Radar | 2 | XValues, YValues, Labels (Radar has Angle and Radius)
Arrow | 4 | StartXValues, StartYValues, XLabel, EndXValues, EndYValues
Bezier | 2 | XValues, YValues, XLabel
Donut | 2 | Angle, YValues, Labels
Smith | 2 | Resistance, Reactance, Labels
Pyramid | 2 | XValues, YValues, XLabels
Map | 3 | XValues, YValues, Polygons, Labels
Gauge | 1 | YValues
Financial |  |
Candle | 5 | OpenValues, CloseValues, HighValues, LowValues, DateValues
Volume | 2 | XValues, YValues (VolumeValues), XLabel
Point & Figure | 5 | OpenValues, CloseValues, HighValues, LowValues, DateValues
Stats |  |
Error | 3 | XValues, YValues, XLabel, StdErrorValues
Error Bar | 3 | XValues, YValues, XLabel, ErrorValues
High-Low | 3 | XValues, YValues, LowValues, XLabel
Histogram | 2 | XValues, YValues, XLabel
BoxPlot | 2 | XValues, SamplesValues, Label
Horizontal BoxPlot | 2 | XValues, SamplesValues, Label
Funnel | 3 | XValues, QuoteValues, OpportunityValues, XLabel

Labelling can be used to extend the value of a 2 variable Series Type. See the example below that uses 3 instances of the Bar Series type in the same Chart.

Example

Uses Bar Series types

Product code | Month | Quantity produced
10 | Jan | 300
10 | Feb | 325
10 | Mar | 287
12 | Jan | 175
12 | Feb | 223
12 | Mar | 241
14 | Jan | 461
14 | Feb | 470
14 | Mar | 455

In its simplest form, the data produces the following Chart, grouping the information by month:

or (grouping by product):

We have added new values to the table above (Stock).

Product code | Month | Quantity produced | Stock level
10 | Jan | 300 | 600
10 | Feb | 325 | 715
10 | Mar | 287 | 676
12 | Jan | 175 | 245
12 | Feb | 223 | 270
12 | Mar | 241 | 315
14 | Jan | 461 | 800
14 | Feb | 470 | 755
14 | Mar | 455 | 835

The values of stock in the table are generally higher than those of monthly production so displaying them gives the following chart (2D this time). The Chart uses Line Series to differentiate Stocks.

Adding data to a Series

Most Series types (other than ODBC datasources Tutorial 8 and Functions Tutorial 7) use the Add and ADDXY methods for adding data. There are some exceptions, see the following table for examples of how they can differ:

Series Type | Add Series points | Delete Series points
Basic |  |
Gantt | GanttSeries.AddGantt GanttSeries.AddGanttColor | Series.Delete Series.DeleteRange
Shape | ShapeSeries.X0, ShapeSeries.Y0, ShapeSeries.X1, ShapeSeries.Y1 | TChart.RemoveSeries (Each Shape is a unique Series)
Bubble | BubbleSeries.AddBubble | Series.Delete Series.DeleteRange
Line | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Bar | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
HorizBar | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Area | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Point | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Pie | Series.Add Series.AddNull Series.AddArray | Series.Delete Series.DeleteRange
Fast Line | FastLineSeries.AddRealTime Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
HorizLine | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
HorizArea | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
3D |  |
Surface | SurfaceSeries.AddXYZ SurfaceSeries.AddArrayXYZ SurfaceSeries.AddArrayGrid | Series.Delete Series.DeleteRange
Contour | ContourSeries.AddXYZ ContourSeries.AddArrayXYZ ContourSeries.AddArrayGrid | Series.Delete Series.DeleteRange
Waterfall | Waterfall.AddXYZ Waterfall.AddArrayXYZ Waterfall.AddArrayGrid | Series.Delete Series.DeleteRange
Color Grid | ColorGrid.AddXYZ ColorGrid.AddArrayXYZ ColorGrid.AddArrayGrid | Series.Delete Series.DeleteRange
Vector 3D | Vector3D.AddVector Vector3D.AddXYZ Vector3D.AddArrayXYZ Vector3D.AddArrayGrid | Series.Delete Series.DeleteRange
Tower | Tower.AddXYZ Tower.AddArrayXYZ Tower.AddArrayGrid | Series.Delete Series.DeleteRange
Point3D | Point3DSeries.AddXYZ | Series.Delete Series.DeleteRange
Triangle Surf. | TriSurface.AddXYZ TriSurface.AddArrayXYZ TriSurface.AddArrayGrid | Series.Delete Series.DeleteRange
Other |  |
Bar 3D | Bar3D.AddBar Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Image Bar | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Wind Rose | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Clock | None | None
Line Point | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Bar Join | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Calender | Calendar.Date | None
Big Candle |  |
ImagePoint | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
DeltaPoint | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Extended |  |
Polar | PolarSeries.AddPolar | Series.Delete Series.DeleteRange
Radar | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Arrow | ArrowSeries.AddArrow | Series.Delete Series.DeleteRange
Bezier | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Donut | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Smith | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Pyramid | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Map | Map.Shapes.Add | Series.Delete Series.DeleteRange
Gauge | Gauge.Value | None
Financial |  |
Candle | CandleSeries.AddCandle | Series.Delete Series.DeleteRange
Volume | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
Point & Figure | PointFigure.AddOHLC | Series.Delete Series.DeleteRange
Stats |  |
Error | ErrorSeries.AddErrorBar | Series.Delete Series.DeleteRange
Error Bar | ErrorBarSeries.AddErrorBar | Series.Delete Series.DeleteRange
High-Low | HighLow.AddHighLow | Series.Delete Series.DeleteRange
Histogram | Series.Add Series.AddXY Series.AddNull Series.AddNullXY Series.AddArray | Series.Delete Series.DeleteRange
BoxPlot | BoxPlot.Median BoxPlot.Quartile1 BoxPlot.Quartile3 BoxPlot.InnerFence1 BoxPlot.InnerFence3 BoxPlot.OuterFence1 BoxPlot.OuterFence3 | TChart.RemoveSeries (Each BoxPlot is a unique Series)
Horizontal BoxPlot | BoxPlot.Median BoxPlot.Quartile1 BoxPlot.Quartile3 BoxPlot.InnerFence1 BoxPlot.InnerFence3 BoxPlot.OuterFence1 BoxPlot.OuterFence3 | TChart.RemoveSeries (Each BoxPlot is a unique Series)
Funnel | Funnel.AddSegment | Series.Delete Series.DeleteRange

Note that Series that do not use the Add or AddXY method, have their Series specific data add method accessible in the series."as[SeriesType]" property (eg. AddCandle at Series.asCandle.AddCandle; AddGantt at Series.asGantt.AddGantt). See the note on Typecasting.

Colour

Colour may be manually added for a point when adding the point

Example

TChart1.Series(0).Add 46, "My first value", vbYellow

Alternatively use the TeeChart constant clTeeColor, telling TeeChart to allocate a colour. TeeChart will choose one of up to 16 unique and as yet unused colours for each new Series.

Example

TChart1.Series(0).Add 46, "My first value", clTeeColor

A 'Non-colour' may be added for a Point to reserve a space for the value in the ValueList without it showing on the Chart.

Example

TChart1.Series(0).Add 46, "My hidden value", clNone

Deleting data points from a Series

Use Series.Delete to delete a point from a Series.

Example

TChart.Series(0).Delete(7) ; (8th point - Points index start at zero)

Point ranges may be deleted from a Series:

Private Sub Command1_Click()
TChart1.Series(0).DeleteRange 5, 5 '(Deletes points 5, 6, 7, 8, & 9 from the Series)
End Sub

Private Sub Form_Load()
With TChart1
    .AddSeries scLine
    .Series(0).FillSampleValues 20
End With
End Sub

Adding Null points to a Series

See the table Adding data to a Series for a list of Series Types that support the AddNull method. As the name suggests, AddNull will add a Null point to the Series allowing you to define a label for the point but leaving a break in the Series at that point. In the case of a Line Series, the last point before the break will not join to the first point after the break. See Series.AddNull and Series.AddNullXY.

example

TChart1.Series(0).AddNull "my null value"

Mixing Series Types on a Chart

TeeChart Pro offers an empty Chart Canvas as a backdrop to data Series. That means that no Chart types are predefined. You define the Chart type you require as a mix of the Series Types that you wish to display. Due to the specialised nature of some Series types it is impractical to mix that Series type with another on a Chart. TeeChart helps you by greying out unsuitable Series types in the Chart Gallery when you arrive to add a new Series. There is no practical limit to the number of Series that you can put in one Chart.

Adding New Series

Add a Series using the Chart Editor (see Tutorial 1) or by code.

Example

TChart1.AddSeries(scLine)  ' Adds a Line Series

(*Note. Microsoft's Implementation of VBScript in internet Explorer does not support the TeeChart Enum constants (scLine, scBar, etc.). You must use the integer equivalent (0,1, etc.) to add a new Series type. See ESeriesClass for a full list. This rule applies to all use of TeeChart ENum constants with VBscript.

Example

TChart1.AddSeries(0)  ' Adds a Line Series (vbscript)

See the 'Walk-through VBScript examples' )

Series are added to the SeriesList accessible by Index, TChart1.Series(index), beginning with 0 for the first Series. TeeChart Pro adds a default name for the Series (Series1, Series2, etc.). You may modify the name using the Series.Title property.

Choose Axes for a Series

Series added to the Chart will automatically take the Left and Bottom axes as their reference axes. You may change the reference axes in the Chart Editor by selecting the Series General page for the relevant Series. There are 4 axes available, Top, Left, Bottom and Right. By code, changing the axes will look like this:

With TChart1.Series(0)
 .HorizontalAxis = aTopAxis
 .VerticalAxis = aRightAxis
End With

More than 1 Series may be associated with each Axis. TeeChart will decide the best scale to fit the Series matched to the Axis but you may change Axis scales yourself (See the Axis Tutorial). Additional axes may be added, they will copy the scales associated with their counterpart from the first 4 axes (see the Tutorial section Additional axes).

Connecting Series

You may use a Series as the datasource for another Series. This can be done with the Chart Editor by setting the datasource for the 2nd Series. Go to the Series tab, Datasource page. Select 'Function' as the datasource type. Two Listboxes will appear, available Series and Selected Series. Select the Series you wish to use as the datasource for the present Series, then, in the Combobox above, entitled Function:, select Copy as the function type. Note that any Series, in this way, may be defined as a function of any other Series and the Function Type may be any of the list available in the Function combobox. To do the same by code see below:

With TChart1.Series(1)
  .DataSource = "Series1"  '  Series1 es Series(0)
  .SetFunction tfCopy
End With

See tutorial 7 - Working with Functions for more information about how to use TeeChart functions.

Changing Series order

Changing series order is very easy with the Chart Editor. Go to the front page of the Editor and highlight the series that you wish to move. Use the arrow buttons on the right to move the Series up or down in the Series order. Series order will decide the relative display position of the Series in the Chart with respect to other Series. Setting a Series to 'Active=False' will hide the Series from the Chart but maintain its data content intact.

To change series order by code use TChart.ExchangeSeries.

TChart1.ExchangeSeries 0, 1  ' Change Series(0) with Series(1) in the index order

*Note. After exchanging Series, the index for the Series will be changed. Thus the line of code above will perpetually interchange the 2 Series '0' and '1' if the code is rerun, as 0 becomes 1 and 1 becomes 0.

Series Value list

TeeChart Series store their values in a Valuelist accessible and modifiable via the ValueList Interface. See the Visual Basic example code entitled "Interactive" below the examples Folder for a working example of the techniques outlined below.

Accessing Series Values

You may access any value in the list:

Example

msgbox TChart1.Series(0).XValues.Value(3)
'Displays value of 4th point (index starts at 0) in Series0

Values accessed in this way may be used to set traps on Series data:

With TChart1.Series(0)
   For t = 0 To .Count - 1
     If .YValues.Value(t) > 900 Then
       MsgBox "Value: " & .XValues.Value(t) & ", " _
              & .YValues.Value(t) & " exceeds limit"
     End If
   Next t
End With

The same value may be obtained via the point ValueIndex used by some Series methods and several Chart events.

Example

Private Sub TChart1_OnClickSeries(ByVal SeriesIndex As Long, ByVal ValueIndex As Long, ByVal Button As TeeChart.EMouseButton, ByVal Shift As TeeChart.EShiftState, ByVal X As Long, ByVal Y As Long)
If SeriesIndex = 0 Then
  MsgBox "ValueIndex is: " & ValueIndex
  MsgBox "Point's Y value is: " & TChart1.Series(SeriesIndex).YValues.Value(ValueIndex)
End If
TChart1.StopMouse  'Use Stopmouse to prevent Zoom event activating
End Sub

Example using Values

This code modifies the value of a BarSeries Bar according to the user's mouseclick. See TeeChart's Interactive Visual Basic demo.

Example

'Use the OnClickSeries or OnclickBackground event to determine where the user has clicked.
Private Sub TChart1_OnClickBackground(ByVal Button As TeeChart.EMouseButton, ByVal Shift As TeeChart.EShiftState, ByVal X As Long, ByVal Y As Long)
If CInt(TChart1.Axis.Bottom.CalcPosPoint(X)) > -1 Then
  Select Case Button
  Case 1
    UpdatePoint CInt(TChart1.Axis.Bottom.CalcPosPoint(X)), CInt(TChart1.Axis.Left.CalcPosPoint(Y))
  End Select
End If
End Sub

Private Sub TChart1_OnClickSeries(ByVal SeriesIndex As Long, ByVal ValueIndex As Long, ByVal Button As TeeChart.EMouseButton, ByVal Shift As TeeChart.EShiftState, ByVal X As Long, ByVal Y As Long)
  UpdatePoint ValueIndex, CInt(TChart1.Axis.Left.CalcPosPoint(Y))
End Sub

In both cases call the UpdatePoint Sub routine to modify the Bar's value:

Private Sub UpdatePoint(Bar, Y As Double)
  If Bar < TChart1.Series(0).Count Then
    TChart1.Series(0).YValues.Value(Bar) = Int(Y)
  End If
End Sub

Series events

The previous section introduces some use of Series events. This section shows some additional uses.

OnClickSeries

You may use the OnClickSeries event to obtain almost any information about a Series (see the section, Accessing Series Values).

'These examples apply to a Series with Datetime data
'eg These test values may be used for the following event examples
Private Sub Command1_Click()
 TChart1.AddSeries scLine
 With TChart1.Series(0)
  .XValues.DateTime = True
  .asLine.Pointer.Visible = True
  .Marks.Visible = True
  'Here with European dateformat
  .AddXY DateValue("1/1/1999") + TimeValue("11:59:00"), 45, "", clTeeColor
  .AddXY DateValue("1/1/1999") + TimeValue("21:59:00"), 23, "", clTeeColor
  .AddXY DateValue("2/1/1999") + TimeValue("11:59:00"), 43, "", clTeeColor
  .AddXY DateValue("2/1/1999") + TimeValue("21:59:00"), 12, "", clTeeColor
  .AddXY DateValue("3/1/1999") + TimeValue("10:59:00"), 12, "", clTeeColor
  .AddXY DateValue("3/1/1999") + TimeValue("21:59:00"), 11, "", clTeeColor
  .AddXY DateValue("4/1/1999") + TimeValue("11:59:00"), 34, "", clTeeColor
  .AddXY DateValue("4/1/1999") + TimeValue("21:59:00"), 15, "", clTeeColor
  .AddXY DateValue("4/1/1999") + TimeValue("23:59:00"), 28, "", clTeeColor
  .AddXY DateValue("5/1/1999") + TimeValue("09:59:00"), 32, "", clTeeColor
  .AddXY DateValue("5/1/1999") + TimeValue("21:59:00"), 32, "", clTeeColor
 End With
 TChart1.Axis.Bottom.SetMinMax TChart1.Series(0).XValues.First, _
                               TChart1.Series(0).XValues.Last + (2 / 12)
End Sub
You could use this event to display Series 'Clicked' values
Private Sub TChart1_OnClickSeries(ByVal SeriesIndex As Long, ByVal ValueIndex As Long, ByVal Button As TeeChart.EMouseButton, ByVal Shift As TeeChart.EShiftState, ByVal X As Long, ByVal Y As Long)
  'The below will show the Value of the nearest Point, not the exact Axis value at the clicked X and Y.
  MsgBox ("Date is:" & Format(TChart1.Series(SeriesIndex).XValues.Value(ValueIndex), "dd/mm/yyyy hh:mm:ss") _
            & " Value is:" & TChart1.Series(SeriesIndex).YValues.Value(ValueIndex))
  TChart1.StopMouse
End Sub
Or alternatively:
Private Sub TChart1_OnClickSeries(ByVal SeriesIndex As Long, ByVal ValueIndex As Long, ByVal Button As TeeChart.EMouseButton, ByVal Shift As TeeChart.EShiftState, ByVal X As Long, ByVal Y As Long)
  'The below will show the exact Axis values at the X,Y clicked.
  MsgBox ("Date is:" & Format(TChart1.Series(SeriesIndex).XScreenToValue(X), "dd/mm/yyyy hh:mm:ss") _
             & " Value is:" & TChart1.Series(SeriesIndex).YScreenToValue(Y))
  TChart1.StopMouse
End Sub

OnGetSeriesPointerStyle

For those Series that use the TChart Pointer, you may access and modify the Pointer using the OnGetSeriesPointer event:

'Drawing an Uptriangle if the Point is higher than the last, DownTriangle if lower, etc.
Private Sub TChart1_OnGetSeriesPointerStyle(ByVal SeriesIndex As Long, ByVal ValueIndex As Long, AStyle As TeeChart.EPointerStyle)
 If ValueIndex > 0 Then
   If TChart1.Series(SeriesIndex).YValues.Value(ValueIndex) > TChart1.Series(SeriesIndex).YValues.Value(ValueIndex - 1) Then
     AStyle = psTriangle
   ElseIf TChart1.Series(SeriesIndex).YValues.Value(ValueIndex) < TChart1.Series(SeriesIndex).YValues.Value(ValueIndex - 1) Then
     AStyle = psDownTriangle
   Else
     AStyle = psDiamond
   End If
 Else
   AStyle = psDiamond
 End If
End Sub

OnGetSeriesMark

Use the OnGetSeriesMark event to modify the Mark contents at runtime:

This code varies the Marktext according to the value relative to the last Arrow lengths are changed too. TeeChart supports the dragging of Marks in cases of overlapping, see the VB 'Moving Marks' example in the VB examples folder

Private Sub TChart1_OnGetSeriesMark(ByVal SeriesIndex As Long, ByVal ValueIndex As Long, MarkText As String)
 If ValueIndex > 0 Then
   If TChart1.Series(SeriesIndex).YValues.Value(ValueIndex) > TChart1.Series(SeriesIndex).YValues.Value(ValueIndex - 1) Then
     MarkText = MarkText & " (Up)"
   ElseIf TChart1.Series(SeriesIndex).YValues.Value(ValueIndex) < TChart1.Series(SeriesIndex).YValues.Value(ValueIndex - 1) Then
     TChart1.Series(SeriesIndex).Marks.ArrowLength = 5
     MarkText = MarkText & Chr$(13) & "(Down)"
   Else
     TChart1.Series(SeriesIndex).Marks.ArrowLength = 25
     MarkText = MarkText & Chr$(13) & "(No change)"
   End If
 End If
End Sub

OnMouseEnterSeries and OnMouseLeaveSeries

An example of the Series events can be seen below:

Private Sub Form_Load()
With TChart1
    .Aspect.View3D = False
    .AddSeries scBar
    .Series(0).FillSampleValues 10
    .Series(0).Marks.Visible = False
End With
End Sub

Private Sub TChart1_OnMouseEnterSeries(ByVal SeriesIndex As Long)
Dim clicked As Long
  clicked = TChart1.Series(SeriesIndex).GetMousePoint

  ' Show Series name and point index and value
  Label1.Caption = "Series: " + TChart1.Series(SeriesIndex).Name + _
                 "  point:" + Str(clicked) + _
                 "  value:" + Str(TChart1.Series(SeriesIndex).YValues.Value(clicked))
End Sub

Private Sub TChart1_OnMouseLeaveSeries(ByVal SeriesIndex As Long)
  Label1.Caption = ""
End Sub


Tutorial 7 - Working with Functions

Function Types

Function characteristics
Adding a Function
Defining a datasource
Function Period
Period Style

Function Types

Function characteristics

A TeeChart Pro Function is a Series, that can be of almost any Series Type, to which an algebraic function is applied and for which the datasource is another Chart Series.

All Functions derive from the Teefunction Class and inherit TeeFunction's Period property.

TeeChart Pro offers following list of predefined functions:

Function Type | No. of inputs | Description
Standard |  |
Add | Unlimited | Plots sum of inputs
Subtract | Unlimited | Plots value of inputs subtracted in descending order of inclusion
Multiply | Unlimited | The Multiply Function plots value of inputs multiplied
Divide | Unlimited | The Divide Function plots inputs divided in descending order of inclusion
High | Unlimited | The High Function plots high point of inputs
Low | Unlimited | The Low Function plots low point of inputs
Average | Unlimited | The Average Function will calculate the average of every group of Period points
Y=F(X) | None | Draws a user defined function
Count | Unlimited | Counts the number of Series Points in the Chart
Extended |  |
Smoothing | 1 | Created a smoothed line joining the points from a given source series
Exponential Average | 1 | Exponential average based on Weight
Standard Deviation | 1 | Maps the Standard Deviation (or Complete Standard Deviation) of every group of Period points
Root Mean Square | 1 | (RMS) Result = Sqrt( Sum( Square(Value) ) ) / NumValues )
Cross Points | Unlimited | Highlights where two Line series cross over each other
Peformance | 1 | Percentage change from one series point to the next
Curve Fitting | 1 | Draws curve through data inputs using the TypeFitting formula
Trend | 1 | Draws best trend line through points of input Series
Exponential Trend | 1 | Trend with exponential weighting
Cumulative | Unlimited | Constructs a line based on the cumulative values of the input
Financial |  |
ADX | 1 | Financial function. Average Directional Change
R.S.I. | 1 | RSI = 100.0 - ( 100.0 / ( 1.0 + Abs( Ups / Downs ) ) )
Moving Average | 1 | The Moving Average Function will calculate the simple or weighted average of every group of Period points
Exponential Moving Average | 1 | Uses the following formula: FP = 2 / ( Period + 1 )
Momentum | 1 | Each Y value is the current point's Y value less the last Period point's Y value
Momentum Division | 1 | Ratio of value compared to previous 'nth' value
MACD | 1 | Financial function. Moving Average Convergence Divergence
Stochastic | 1 | Financial function. Calculates the highest and lowest value in a given period
Bollinger | 1 | Financial function. Uses Moving average (may be exponential) and standard deviation
Compression | 1 | Calculates the highest and lowest value from a source series during a datetime period
Closed Location Value | 1 | CLV = ( (Close-Low)-(High-Close))/(High-Low)
On Balance Volume | 1 | For each point in the OHLC series, the Close price is compared to the Open price. If the Close is higher, the Volume value for that point is added. If the Close is lower, the Volume value is lowered.
Commodity Channel Index | 1 | Financial Indicator used to identify cyclical turns in commodities
Volume Oscillator | 1 | Calculates the difference between two exponential moving averages ( a - b)

Several Function types support only one input Series. However it is possible to chain link Functions, thus, for example, taking the average of several Series in your Chart to create an Average Function Series, then identify the Trend of the average by using the Average Function as the input to the Trend Function.

Adding a Function

With the Chart Editor, on the First Chart page, select the Add button as if to add a new Series to the Chart. In the TeeChart Gallery choose the Functions tab to select the Function you require. Each Function is presented as a Line Series, you may change the Series Type associated with the Function later by choosing the Change button on the first Chart Page. Function definitions are easily changed afterwards on the Datasource page of the Function Series. Here, just as easily, you may change the definition of a normal Series that you have added to the Chart to that of a Function (Function is really a definition of datasource, not a definition of Series Type).

The image below shows the Datasource page when editing a Function. The Line Series (Name "Series1", Title "Average") is defined. The left listbox at the bottom of the Datasource page shows other Series in the Chart available for input (here "Series0").

Assuming we start with a completely empty Chart here are the steps in code to build a simple Series-Function related Chart.

With TChart1
  'Add 2 data Series
  .AddSeries scBar
  .AddSeries scBar
  ' Populate them with data (here random)
  .Series(0).FillSampleValues 10
  .Series(1).FillSampleValues 10
  ' Add a series to be used for an Average Function
  .AddSeries scLine
  'Define the Function Type for the new Series
  .Series(2).SetFunction tfAverage
  'Define the Datasource for the new Function Series
  'Datasource accepts the Series titles of the other 2 Series
  .Series(2).DataSource = "Series0,Series1"
   '    *Note - When populating your input Series manually you will need to
   '    use the Checkdatasource method
   '    - See the section entitled 'Defining a Datasource'
  'Change the Period of the Function so that it groups averages
  'every 2 Points
  .Series(2).FunctionType.Period = 2
End With

We can add another Function to tell us something about the previous Function

With TChart1
  'Add another Series to be used for a 2nd Function
  .AddSeries scLine
  'Define the Function Type for the new Series
  .Series(3).SetFunction tfHigh
  'Define the Datasource for the new Function Series
  'Use the existing Function (Series2) as input
  .Series(3).DataSource = "Series2"
  'Leave the Period at default 0 (No Period set) to draw
  'A line at Highest of all points of the Average Function
End With

Defining a datasource

The examples in the previous section highlight the use of Datasource for populating a Function by code. Series use datasource for defining the input for a Function or to define a Series ODBC datasource (see the Tutorial about accessing databases).

Using the Chart Editor, after adding a Function, the Function Series' Datasource page will show a list of available series for inclusion in the function definition. Here you may change the Function Type you wish to apply to the Series and select Series from the Left listBox "Available" and add them to the right Listbox,"Selected".

Datasource by code uses the Series.Datasource property.

Example

Suppose we have 2 data Series in a Chart. We add a Function composed of the average of the 2 Series:

With TChart1
  .AddSeries scLine
  'Define the Function Type for the new Series
  .Series(2).SetFunction tfAverage
  .Series(2).DataSource = "Series0,Series1"
End With

We add points to the 2 Series:

Dim t As Integer
With TChart1
  For t = 0 To 10
    .Series(0).Add 2 * t, "", clTeeColor
    .Series(1).Add 3 * t, "", clTeeColor
  Next t
End With

Notice that the Function doesn't display. You need to use the Series.CheckDatasource method to read in values for the Function.

TChart1.Series(2).CheckDataSource
'Read in data for Function

Function definition may be changed at runtime using the Setfunction method to allocate a new Function to the Series.

TChart1.Series(2).Setfunction tfMovavg

with the above line of code, Setfunction changes the Function for Series(2) to a Moving Average.

Function Period

Period is an important property for working with Functions as the Period defines the range of points across which a Function is cyclically applied.

Example

We have 6 data points (e.g. bars of a Bar Series) with values:

3, 8, 6, 2, 9 and 12

We define a Function Series with Period 0 (default) the average drawn is:

6.667

With Period set to 2 we get 3 values of average as output from the function:

5.5, 4 and 10.5

These values will plot centrally in their period range, i.e. The 1st value between bars 1 and 2 of the input series, 2nd value between bars 3 and 4, etc..

You may define Period by selecting the relevant Series and Function in the Datasource page and clicking the "Options" tab or you may modify Period at runtime using FunctionType.

E.g. Where Series 2 is the function series:

TChart1.Series(1).FunctionType.Period=2

Below are 2 Charts that highlight the effect of an applied Period

Period Style

Period can be defined to be a range. This is very useful when using Date-Time series and want to express the "Period" of the function in a date-time step like "OneMonth" or "OneDay". The property "PeriodStyle" controls how is "Period" expressed.

For example you can now plot the "monthly average of sales" function just using a normal "Average" function on a date-time source series and setting the function period to "one month":

'Add a Series and fill it with datetime data values at runtime (or from a database)

TChart1.Series(1).SetFunction tfAverage
TChart1.Series(1).FunctionType.PeriodStyle =psRange
TChart1.Series(1).FunctionType.Period = TChart1.GetDateTimeStep dtOneMonth
TChart1.Series(1).DataSource = "Series0"

This will result in several points, each one showing the "average" of each month of data in Series0.

It’s mandatory that points in the source Series0 should be sorted by date when calculating functions on datetime periods.
The range can also be used for non-datetime series:

TChart1.Series(1).SetFunction tfAverage
TChart1.Series(1).FunctionType.PeriodStyle =psRange
TChart1.Series(1).FunctionType.Period=100
TChart1.Series(1).DataSource= "Series0"

This will calculate an average for each group of points inside every "100" interval.

(Points with X >=0, X<100 will be used to calculate the first average, points with X >=100, X<200 will be used to calculate the second average and so on... ).
Notice this is different than calculating an average for every 100 points.

Use the Period Alignment property to align the function Points within the Series range. The following will plot the Function point at the end of a monthly Period:

TChart1.Series(1).FunctionType.PeriodStyle = psRange
TChart1.Series(1).FunctionType.Period = TChart1.GetDateTimeStep dtOneMonth
TChart1.Series(1).FunctionType.PeriodAlign =paLast
PeriodStyle = OneMonth and PeriodAlign = paLast

As you can see from the picture below, the "average" is plotted at the end of the month.

PeriodStyle = OneMonth and PeriodAlign = paFirst

In this case the "average" is plotted at the beginning of the month.


Tutorial 8 - ADO Database access

Introduction

Connecting to ADO sources at design-time

Dataset
Single Record
Summary

Connecting to ADO sources at run-time

Dataset
Single Record
Summary

Using ADO with Active Server Page scripts

Introduction

Connecting a TeeChart control to ADO databases can be done at design-time using the Chart Editor and at run-time with few lines of code.

Any Series can be connected to ADO tables or queries using the Chart Editor. Every Series can be connected to the same or different table or query using the same or different ADO database.

This design gives you total flexibility on how do you connect Charts to databases, as you aren't restricted to only one database or to only one table or query.

Data is retrieved also at design-time so you see the actual data during development.

Connecting to ADO at design-time

Dataset

At design-time, the steps necessary to connect a Series to an OLE/ODBC datasource are:

  • 1. Place a TChart control on a Form
  • 2. Right-click the TChart control and select "Properties" to show the Chart editor
  • 3. Add a Series to the Chart control (for example a Bar Series)
  • 4. Click on "Series" tab and "DataSource" tab
  • 5. Now click on the combo-box and select "Dataset"
    • At this point you will see this screen:

  • 6. Click the "New..." button to show the Dataset ConnectionString dialog:

    • From here you can either select a Data Link (UDL) file or you can build your own Connection String. In this example we'll select the default Microsoft OLE DB Provider for ODBC Drivers from the Provider tab and the TeeChart Pro Database from the Connection tab:

  • 7. After selecting "OK" on the above screen, select the "Employee" table as shown in the picture below. Here we also have the possibility to create an SQL query instead, or to bring in a text file containing one.

  • 8. Click "OK" to close the ADO Datasource dialog and return to the Chart editor.

    • Now you should define which Fields from the Table or SQL Query should be retrieved and added to the Series. This is done with the Chart editor, by selecting the appropriate fields for each Series part.

  • 9. See the image below, showing the Chart editor DataSource tab with our example selected Fields.

    • Each Series has a "Label" field (which should be of type "String" or "Char") ,and a value field (the "Bar" field for Bar Series), which should be of either integer, floating or date-time field type.

    In this example, we have selected the "LASTNAME" field from the "Employee" table for the Series labels, and the "SALARY" numeric field for the Bar point values.

    See the Dataset combobox in the above picture. This combobox shows the available tables or queries you have created. You can always come to this dialog and select a different dataset, or edit it by clicking the "Edit..." button.

    Now we have assigned the appropriate fields, it's time to see the results.

  • 10. Click the "Close" or the "Apply" button to close the Chart editor and to return to the programming environment.

    • At this time, the TChart control will open the selected ADO database Table or Query, and will start retrieving records and adding values to the selected Series.

    In our example, you'll see at design-time the following Chart:

    Now, if you run the project, the Chart will retrieve all records from ODBC and will add values to the Series. You will see the same Chart you saw at design-time before running the project.

  • 11. Run the application.

    • See also the included ADO examples for Visual Basic under the "Examples" folder.

    Single Record

    At design-time, the steps necessary to connect a Series to a single record of an OLE/ODBC datasource are:

  • 1. Place a TChart control on a Form
  • 2. Right-click the TChart control and select "Properties" to show the Chart editor
  • 3. Add a Series to the Chart control (for example a Bar Series)
  • 4. Click on "Series" tab and "Data Source" tab
  • 5. Now click on the combo-box and select "Single Record"
    • At this point you will see this screen:

  • 6. Click the "New..." button to show the Dataset ConnectionString dialog or select and edit or delete an existing dataset:

    • From here you can either select a Data Link (UDL) file or you can build your own Connection String. In this example we'll select the default Microsoft OLE DB Provider for ODBC Drivers from the Provider tab and the TeeChart Pro Database from the Connection tab:

  • 7. After selecting "OK" on the above screen, select the "Months" table as shown in the picture below. Here we also have the possibility to create an SQL query instead, or to bring in a text file containing one.

  • 8. Click "OK" to close the ADO Datasource dialog and return to the Chart editor.

    • Now you should define which Fields from the Table or SQL Query should be retrieved and added to the Series. This is done with the Chart editor, by selecting the appropriate fields from those available.

  • 9. See the image below, showing the Chart editor DataSource tab with our example selected Fields.

    • In this example, we have selected the all the available fields except the "Year" field.

    See the Dataset combobox in the above picture. This combobox shows the available tables or queries you have created. You can always come to this dialog and select a different dataset, edit it by clicking the "Edit..." button or delete it by clicking the "Delete" button.

    Now we have assigned the appropriate fields, it's time to see the results.

  • 10. Click the "Close" or the "Apply" button to close the Chart editor and to return to the programming environment.

    • At this time, the TChart control will open the selected ADO database Table or Query, and will start retrieving records and adding values to the selected Series.

    In our example, you'll see at design-time the following Chart:

    If you have clicked the "Apply" button rather than the "Close" button and have therefore left the Chart Editor open, you will now be able to navigate through all the records of your DataSet using the navigator buttons on the Data Source page.

    Now, if you run the project, the Chart will retrieve all records from ODBC and will add values to the Series. You will see the same Chart you saw at design-time before running the project.

  • 11. Run the application.

    • See also the included ADO examples for Visual Basic under the "Examples" folder.

    Summary

    At design-time, the steps necessary to create Series which are summeries of an OLE/ODBC datasource are:

  • 1. Place a TChart control on a Form
  • 2. Right-click the TChart control and select "Properties" to show the Chart editor
  • 3. Add a Series to the Chart control (for example a Bar Series)
  • 4. Click on "Series" tab and "Data Source" tab
  • 5. Now click on the combo-box and select "Summary"
    • At this point you will see this screen:

  • 6. Click the "New..." button to show the Dataset ConnectionString dialog or select and edit or delete an existing dataset:

    • From here you can either select a Data Link (UDL) file or you can build your own Connection String. In this example we'll select the default Microsoft OLE DB Provider for ODBC Drivers from the Provider tab and the TeeChart Pro Database from the Connection tab:

  • 7. After selecting "OK" on the above screen, select the "orders" table as shown in the picture below. Here we also have the possibility to create an SQL query instead, or to bring in a text file containing one.

  • 8. Click "OK" to close the ADO Datasource dialog and return to the Chart editor.

    • Now you should define which Fields from the Table or SQL Query should be used to create your summary and added to the Series. This is done with the Chart editor, by selecting the appropriate fields from those available.

  • 9. See the image below, showing the Chart editor DataSource tab with our example selected Fields.

    • In this example, we have calculated the sum of the ITEMTOTAL field and have grouped the results by the SHIPVIA field.

    See the Dataset combobox in the above picture. This combobox shows the available tables or queries you have created. You can always come to this dialog and select a different dataset, edit it by clicking the "Edit..." button or delete it by clicking the "Delete" button.

    Now we have assigned the appropriate fields, it's time to see the results.

  • 10. Click the "Close" or the "Apply" button to close the Chart editor and to return to the programming environment.

    • At this time, the TChart control will open the selected ADO database Table or Query, and will start retrieving records and adding values to the selected Series.

    In our example, you'll see at design-time the following Chart:

    Now, if you run the project, the Chart will retrieve all records from ODBC and will add values to the Series. You will see the same Chart you saw at design-time before running the project.

  • 11. Run the application.

    • See also the included ADO examples for Visual Basic under the "Examples" folder.

    Connecting to ADO at run-time

    Dataset

    The above design-time steps can be reproduced programmatically with few lines of code. This gives you more freedom and control over database operations.

    Repeat the first 3 steps above on a new project and a new Form.

    Every Series has the "DataSource" property, which determines the origin of database values (the Table or Query), and the "YValues.ValueSource" and "LabelsSource" properties to specify which fields we want to plot.

    And the syntax for Series DataSource is:

    ' This example uses Microsoft OLE DB
' ActiveX Data Objects 1.0 Library.
' This library is located at: MSADO10.DLL

' declare a Connection and RecordSet variables...
Dim Data As New ADODB.Connection
Dim Record As New ADODB.Recordset

Data.Open "TeeChart Pro Database", "", ""
Record.Open "employee", Data, adOpenKeyset

'The Recordset variable can now be set
'directly to the DataSource
TChart1.Series(0).DataSource = Record

    The syntax for LabelsSource and YValues.ValueSource properties is:

    TChart1.Series(0).YValues.ValueSource = "SALARY"
TChart1.Series(0).LabelsSource = "LASTNAME"

    SQL queries become incorporated into the the opening of the Recordset:

    Record.Open "select * from [employee] where [Salary] > 42500", Data, adOpenKeyset

    It is recommended you set the above properties in that order. First set the DataSource and then the LabelsSource and the YValues.ValueSource properties.

    To disconnect a Series from a datasource, you should simply do this:

    TChart1.Series(0).DataSource = ""

    In case the database values are changed and you want to "refresh" the connection and retrieve the values again, you should do this:

    TChart1.Series(0).CheckDataSource

    The "CheckDataSource" method will force the Series to retrieve all records again.

    All Series have also the "XValues.ValueSource" property. This property is used for XY charting only (when you have an X coordinate for each point).

    You may also wish to programmatically link a UDL file as the Datasource of a TeeChart. This can be achieved using the following syntax:

    Dim Data As New ADODB.Connection
Dim Record As New ADODB.Recordset

Data.Open "File Name=C:\Program Files\Common Files\System\Ole DB\Data Links\TEECHARTDB.udl"
Record.Open "employee", Data, adOpenKeyset

TChart1.Series(0).DataSource = Record

    An error will be raised if TeeChart can not locate the datasource OLE/ODBC DSN, or it can not open the Table or SQL query you specify. Please see the ADO Databases example (\Examples\Visual Basic 6\ADO Databases) for a fully coded project.

    Single Record

    The above design-time steps can be reproduced programmatically with few lines of code.

    Repeat the first 3 steps above on a new project and a new Form and add an additional four CommandButtons to it.

    To code a Series Single Record is relatively simple, differing from the above Series Dataset only in the use of the DataSourceType property and the syntax of the ValueSource property. These differences can be seen in the coded example below:

    Dim rst

Private Sub Command1_Click()
  rst.MovePrevious
  CheckKeys
End Sub

Private Sub Command2_Click()
  rst.MoveNext
  CheckKeys
End Sub

Private Sub Command3_Click()
  rst.MoveLast
  CheckKeys
End Sub

Private Sub Command4_Click()
  rst.MoveFirst
  CheckKeys
End Sub

Private Sub Form_Load()
  Set Conn = CreateObject("ADODB.Connection")
  Set rst = CreateObject("ADODB.Recordset")
  Conn.Open "DSN=TeeChart Pro Database"
  rst.Open "select * from months", Conn, 1, 1

  With TChart1.Series(0)
    ' ****************************************************************
    ' The DatasourceType line should be run before the Recordset is
    ' applied to the Series. The default is dstAllRecords so this
    ' method only really needs to be called for Single Record charting.
    ' ****************************************************************
    .DatasourceType = dstSingleRecord
    .DataSource = rst
    .YValues.ValueSource = "Jan;Feb;Mar;Apr;May;Jun;Jul;Aug;Sep;Oct;Nov;Dec"
  End With

  With TChart1.Tools
    .Add tcAnnotate
    .Items(0).asAnnotation.Position = ppLeftTop
  End With

  CheckKeys
End Sub

Private Sub CheckKeys()
  TChart1.RefreshData
  TChart1.Tools.Items(0).asAnnotation.Text = "Year: " & rst!Year
  If rst!Year = "2017" Then
     Command4.Enabled = False
     Command1.Enabled = False
     Command2.Enabled = True
     Command3.Enabled = True
  ElseIf rst!Year = "2000" Then
     Command2.Enabled = False
     Command3.Enabled = False
     Command1.Enabled = True
     Command4.Enabled = True
  Else
     Command4.Enabled = True
     Command1.Enabled = True
     Command2.Enabled = True
     Command3.Enabled = True
  End If
End Sub

    For further details on the manipulation of the TeeChart DataSource, ValueSource and LabelSource properties please refer back to the Dataset section of this Tutorial.

    Summary

    The above design-time steps can be reproduced programmatically with few lines of code.

    Repeat the first 3 steps above on a new project and a new Form and add an additional two ComboBoxes to it.

    To code a Series Summary is relatively simple, differing from the above Series Dataset only in the syntax of the ValueSource property. This difference can be seen in the coded example below:

    Private Sub Form_Load()
  Combo1.Text = "ShipVia"
  Combo2.Text = "Sum"
  Combo1.AddItem "EmpNo", 0
  Combo1.AddItem "PaymentM", 1
  Combo1.AddItem "SaleDate", 2
  Combo1.AddItem "ShipVia", 3
  Combo1.AddItem "Terms", 4
  Combo2.AddItem "Sum", 0
  Combo2.AddItem "Count", 1
  Combo2.AddItem "High", 2
  Combo2.AddItem "Low", 3
  Combo2.AddItem "Average", 4
  Set Conn = CreateObject("ADODB.Connection")
  Set rst = CreateObject("ADODB.Recordset")
  Conn.Open "DSN=TeeChart Pro Database"
  rst.Open "select * from orders", Conn, 1, 1

  With TChart1.Series(0)
    .DataSource = rst
    .YValues.ValueSource = "#Sum#AmntPaid"
    .LabelsSource = "ShipVia"
  End With
End Sub

Private Sub Combo1_Change()
  Combo1_Click
End Sub

Private Sub Combo1_Click()
  With TChart1
    Select Case Combo1.ListIndex
      Case 0
        .Series(0).LabelsSource = "EmpNo"
      Case 1
        .Series(0).LabelsSource = "PaymType"
      Case 2
        .Series(0).LabelsSource = "#Year#SaleDate"
      Case 3
        .Series(0).LabelsSource = "ShipVia"
      Case 4
        .Series(0).LabelsSource = "Terms"
    End Select
  End With
End Sub

Private Sub Combo2_Change()
  Combo2_Click
End Sub

Private Sub Combo2_Click()
  With TChart1
    Select Case Combo2.ListIndex
      Case 0
        .Series(0).YValues.ValueSource = "#Sum#AmntPaid"
      Case 1
        .Series(0).YValues.ValueSource = "#Count#AmntPaid"
      Case 2
        .Series(0).YValues.ValueSource = "#High#AmntPaid"
      Case 3
        .Series(0).YValues.ValueSource = "#Low#AmntPaid"
      Case 4
        .Series(0).YValues.ValueSource = "#Avg#AmntPaid"
    End Select
  End With
End Sub

    For further details on the manipulation of the TeeChart DataSource, ValueSource and LabelSource properties please refer back to the Dataset section of this Tutorial.

    Using ADO with Active Server Page scripts

    You may connect Datasources via ASP. The Environment.NoPromptDBConnect property should be set to True to support ASP's connection mode. See the Internet Applications tutorial for more about ASP.


Tutorial 9 - Internet applications

General techniques
*Special note Zoom and Scroll

Options for delivering a web Charting application

'Live' TeeChart in the browser page as an ActiveX control
'Live' TeeChart on the web page using TeeChart template files
TeeChart on the web page as a static JPEG file
TeeChart and ASP run server-side in IIS4, IIS5 & IIS6 servers
TeeChart and ASP.NET
TeeChart CAB files
Version Control
Printing from Internet Explorer

More on Active Server Pages (ASP) and ASP/IIS Servers

Creating an image Charting application with ASP/IIS servers
Creating a Live Charting application with ASP/IIS servers
Streaming Charts directly to the browser
Native TeeChart ODBC access with ASP
Native TeeChart ADO access with ASP
Naming TeeChart files in a multiuser environment
Use of TeeChart constants in ASP

General techniques

Adding TeeCharts to your internet/intranet web pages may be done in two key ways, depending on where and how you want your data to be retrieved and what user options you wish to present at the browser.

The TeeChart ActiveX control can be inserted in HTML pages using the HTML <OBJECT> tag as follows:

<OBJECT  classid="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258"
  codebase="TeeChart2017.ocx#Version=9,0,0,0"
  id=TChart1
  TYPE="application/x-oleobject"
  width=500
  height=250
  align=center
  hspace=0
  vspace=0
  >
</OBJECT>

This works only using Microsoft Internet Explorer web browser version 3.02 or greater. Netscape does support the use of ActiveX Controls on the page but you must use an Add-in that supports ActiveX.

Another way to transfer Charts is to save them as image files in JPEG/PNG or GIF format (Internet Explorer also supports metafile). This does not have the advantages of a "live" Chart, such as mouse clicks, real-time animation, scrolling, etc, but works with almost any browser.

Chart controls can be saved to JPEG format with this method:

  TChart1.Export.asJPEG.SaveToFile

Example of use:

  With TChart1
    .Width = 400
    .Height = 300
    .Export.asJPEG.CompressionQuality = 50
    .Export.asJPEG.SaveToFile "c:\temp\myJPGFile.jpg"
  End With

Bitmaps can also be saved to file in GIF, PCX or PNG formats:

With TChart1
    .Export.asBMP.SaveToFile( "c:\MyBMP.png" )
    .Export.asGIF.SaveToFile( "c:\MyGIF.png" )
    .Export.asJPEG.SaveToFile( "c:\MyJPEG.png" )
    .Export.asMetafile.SaveToFile( "c:\MyMetafile.wmf" )
    .Export.asPCX.SaveToFile( "c:\MyPCX.pcx" )
    .Export.asPNG.SaveToFile( "c:\MyPNG.png" )
End With

An alternative to saving to disk file is to use the SaveToStream method to create a binary stream that returns the BMP, GIF, JPEG, Metafile, PCX or PNG Chart directly to the browser. All techniques are examined in more detail later in this tutorial.

See the "HTML HotSpot MAP" example under \Examples\Visual Basic 6 folder and as an ASP file in the TeeChart ASP examples to create hot-spot clicking maps.

When using Chart objects, these can be manipulated at the client side using Microsoft's Visual Basic Script. (See next Tutorial)

Data values can be added to the Chart objects using VBScript or importing already saved native Chart files or Text files from an URL internet address.

Charts can be saved to native format using this method:

TChart1.Export.asNative.SaveToFile( "c:\MyTEEwithSeriesData.tee", True )

Charts can be saved to text format using this method:

TChart1.Export.asText.SaveToFile( "c:\myTXT.txt" )

And can then be loaded from the client machine with this code:

TChart1.Import.LoadFromFile( "\\MyServer\MyCharts\MyChart.tee" )

and

TChart1.Import.LoadFromFile( "\\MyServer\MyCharts\MyTXT.txt" )

Or from an URL address:

TChart1.Import.LoadFromURL( "http://www.steema.com/demo.tee" )

and

TChart1.Import.LoadFromURL( "http://www.steema.com/demo.txt" )

On the Server side, you can build ASP pages or ISAPI DLL's to create and return TeeChart Pro controls.

This can be done with TeeChart Pro using Microsoft's OLE Automation.

See the "OLE Automation" example under \Examples\Visual Basic 6 folder.

The syntax for use in VB is as follows. The model, virtually unchanged, may be used when scripting ASP.

Private Sub Command1_Click()
Dim Chart As Object
' create the ole automated object...
Set Chart = CreateObject("TeeChart.TChart")
' set properties...
  Chart.Width = 360
  Chart.Height = 170
  Chart.AddSeries (1)
' add some random values...
  Chart.Series(0).FillSampleValues 6
  Chart.Series(0).ColorEachPoint = True
' save the chart to bitmap file...
  Chart.Export.asBMP.SaveToFile ("c:\mychart.bmp")
' release the object...
Set Chart = Nothing
' load the bitmap file back to Picture control...
Picture1 = LoadPicture("c:\mychart.bmp")
End Sub

*Special note Zoom and Scroll

TeeChart is mousedrag zoomable and scrollable on the browser page in its native <OBJECT> form. However Internet Explorer version 5 has introduced a new requirement to facilitate this functionality, the need for a TeeChart event on the browser page. The event may be empty.

Examples

VbScript
---------
<SCRIPT LANGUAGE=VBSCRIPT>
Sub TChart1_OnAfterDraw()
 'empty
End sub
</SCRIPT>

JScript
--------
<SCRIPT LANGUAGE="JavaScript" FOR="TChart1" EVENT="OnAfterDraw()">
<!--
 //empty
-->
</SCRIPT>

Options for delivering a web Charting application

There are several basic options to delivering a TeeChart Web application. The options available will depend on what Webserver you are running as more recent developments with Microsoft's Web server allow a great deal to be scripted 'server side' for ocx controls.

Web Charting applications can access ADO datasources too. The following sections describe how connectivity would be implemented and what impact that would have on Client-Server configuration requirements.

'Live' TeeChart in the browser page as an ActiveX control

Standard setup
We could consider this as 'Standard' format. This would require the object definition for the TeeChart Control to be placed in an html page to be accessed directly by a client browser (as discussed at the beginning of this tutorial and throughout the next tutorial). The ocx may be present on the client machine or the Activex object definition may point to a server based CAB file. The advantage of the CAB file approach is that you centrally control the version of the ocx that the client machine runs. The next tutorial discusses, in some detail, syntax and scripting options for a TeeChart control on the html page.

ADO/ODBC access
The standard setup will allow ODBC datasources to be accessed from the client machine. When a client browser views a page containing a 'Live' TeeChart control it is launching a local instance of that control, thus any ODBC datasource defined for that Chart must be a local client ODBC User DSN. The local User DSN must be pathed to connect to the central (or local !) database (The exception to this rule lies with ASP applications where you may access the ODBC System DSN at the server only and distribute the generated Chart using the TeeChart .tee format file. See the ASP section).

Example

'VBScript on html page accessing TeeChart OBJECT ID 'Chart'
Chart.Series(0).YValues.ValueSource = "SALARY"
Chart.Series(0).LabelsSource = "LASTNAME"
Chart.Series(0).DataSource="DSN=TeeChart Pro Database; SQL=select * from employee"

or using accessing an ADO Recordset directly:

<SCRIPT LANGUAGE=VBSCRIPT>

Sub FillChart()
'Setup Series
Chart.AddSeries(1)
Chart.Series(0).Marks.Visible=False
Chart.Series(0).ColorEachPoint = True

'Connect to database
Conn.Open "TeeChart Pro Database"
RSt.Open "select * from [employee]", Conn, 1,1

'Connect Series to Recordset
Chart.Series(0).Datasource = RSt
Chart.Series(0).LabelsSource="Lastname"
Chart.Series(0).YValues.ValueSource="Salary"
End Sub

Sub Window_Onload()
FillChart
End Sub

Sub Chart_OnAfterDraw()
End Sub

</SCRIPT>

<OBJECT ID="Chart" WIDTH=450 HEIGHT=290
 CLASSID="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258">
</OBJECT>

<OBJECT ID="Conn"
 CLASSID="CLSID:00000514-0000-0010-8000-00AA006D2EA4">
</OBJECT>

<OBJECT ID="RSt"
 CLASSID="CLSID:00000535-0000-0010-8000-00AA006D2EA4">
</OBJECT>

' When this is run as a clientside script, the User DSN 'TeeChart Pro Database'
' must exist on the Client machine. For ASP datasourced Charts, the DSN only
' needs to reside at the server. See the next section.

For Internet applications it may be impractical to assume that all client machines will have ODBC access to the database server (unless the database is local to each machine). However for Intranet applications this topography may be a viable option. If we assume that "to achieve ODBC access for all clients" is difficult, we may address the issue in other ways, see the following sections.

'Live' TeeChart on the web page using TeeChart template files

TeeChart template files offer the possibility of putting 'Live' (zoomable and scrollable) ADO datasourced Charts on the browser page without the need for the OLE DB or ODBC compliant datasource in each client machine. TeeChart templates are very small files containing Chart data and display properties. The files may be created centrally on or for the Web server and distributed to (made available for) the client browser Charts.

The application could work in this way: You would create a central process (e.g. local executable or dll or an ASP scripted process (see the ASP section) ) that creates a Chart accessing a server based ODBC datasource. The application would save/export (could be at set intervals) the current Chart as a TeeChart template (.tee) file.

Example

Chart1.Export.asNative.SaveToFile( "c:\tempDownloadArea\mychart.tee", True )

..or export the Chart as a stream directly to the browser..

Chart1.Export.asNative.SaveToStream( True )

The html page for the browser would contain the standard OBJECT definition for the TeeChart control and options to refresh the Chart. These could take the form of:

Example

'automatic import when page is loaded
<script language="VBScript"><!--
Sub Window_onload()
  ' importing a Chart saved to disk as a tee file
  TChart1.Import.LoadFromURL("http://www.myweb.com/mychart.tee")
end Sub
--></script>

Or...

'manual import of latest Chart
<script language="VBScript">
SUB ImpChart
TChart1.Import.LoadFromURL("http://www.myweb.com/mychart.tee")
End Sub
</script>
<!--button-->
<input type="button" value="Import Chart"
onclick="ImpChart" name="cdmChart1">

Or...

'Use TeeChart's timer to update at intervals the local Chart
<script language="VBScript">
Sub Window_onload()
  'Activate TeeChart timer
  TChart1.TimerEnabled = True
  TChart1.TimerInterval = 120
end Sub

Sub TChart1_OnTimer()
  'On timer import the latest server Chart
  TChart1.Import.LoadFromURL("http://www.myweb.com/mychart.tee")
End Sub

Or...

' If streaming the Chart to the browser (no temporary files)
' then you could call the asp script that creates and expoirt s the Chart:
TChart1.Import.LoadFromURL("http://www.myweb.com/myscripts/createchart.asp")

</script>

TeeChart on the web page as a static JPEG, PNG, GIF or PCX file

This setup does not require that the Client browser has access to the TeeChart Pro Activex control. Simply create a process on the server that exports to a JPEG, PNG, GIF or PCX chart (see earlier and ASP section of this tutorial). The server application could access any server based OLE DB or ODBC compliant datasources if required. The application's HTML pages would then reference that Chart as a static image file. This approach will be of interest for those wishing to create a Charting application generic and homogeneous to all browser types (for streaming Charts directly to the browser see the Chart streaming section).

TeeChart and ASP run server-side in IIS4, IIS5 & IIS6 servers

TeeChart can be scripted server side with ASP. This would allow, for example, the previous option (JPEG file) to be created with an ASP script. Typical syntax for a script would be as follows: Example

e.g. MyCreateChart.asp file

<!--METADATA NAME="TeeChart Pro Activex control v2017" TYPE="TypeLib"
UUID="{5006E56D-FEDE-4C64-9CC2-78C320929406}"-->

<OBJECT RUNAT=Server ID=MyChart
CLASSID="Clsid:FCB4B50A-E3F1-4174-BD18-54C3B3287258">
REM Object Script
</OBJECT>

<%
Response.BinaryWrite(RunChart)
Function RunChart()
  Dim img
  MyChart.AddSeries(scArea)
  MyChart.Series(0).FillSampleValues(10)
  img = MyChart.Export.asPNG.SaveToStream
  RunChart=img
End Function
%>

The importing page could show the above Chart via an img tag:

<HTML><BODY>
<img src="http://www.myweb.com/myscripts/MyCreateChart.asp">
</BODY></HTML>

Alternatively the CreateObject method, described earlier in this tutorial, may be used to create teeChart with ASP. TeeChart may also be used with Microsoft scriplets. There is an example included with the TeeChart Internet Explorer examples.

TeeChart and ASP.NET

TeeCharts can be displayed as "live" and "static" charts in ASP.NET just as they can in "normal" ASP. To create a static chart in an ASP.NET application, simply follow the steps below

  • Create a new ASP.NET application.
  • Add an Image box to the WebForm.
  • Right Click on the project's References and add in a reference to the TeeChart Pro ActiveX Control v2017 (COM Tab).
  • In the WebForm's Page_Load event, add in the following code (VB.NET example):
    • Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  TChart1.AddSeries(TeeChart.ESeriesClass.scBar)
  TChart1.Series(0).FillSampleValues(10)
  TChart1.Height = Image1.Height.Value
  TChart1.Width = Image1.Width.Value
  TChart1.Export.asPNG.SaveToFile("E:\Inetpub\wwwroot\TestASPNETSol\VBWeb\MyChart.png") 'path to virtual folder
  Image1.ImageUrl = "http://localhost/VBWeb/MyChart.png"
End Sub

    To create a "live" chart, step through the following:

  • Create a new ASP.NET application.
  • Right Click on the project's References and add in a reference to the TeeChart Pro ActiveX Control v2017 (COM Tab).
  • Open the WebForm in HTML view and make sure the BODY of the page looks like this:
    • <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
    </form>
    <OBJECT id="TChart1" style="Z-INDEX: 101; LEFT: 34px; WIDTH: 482px; POSITION: absolute; TOP: 38px; HEIGHT: 358px"
      classid="clsid:FCB4B50A-E3F1-4174-BD18-54C3B3287258" VIEWASTEXT>
      <PARAM NAME="Base64" VALUE="VFBGMAtUQ2hhcnRDaGFydAAETGVmdAIAA1RvcAIABVdpZHRoA+IBBkhlaWdodANmARJUaXRsZS5U
ZXh0LlN0cmluZ3MBBghUZWVDaGFydAAAAAAAAAACAAAAAP////8=">
    </OBJECT>
    <script language="vbscript">
        Sub Window_Onload()
            TChart1.Import.LoadFromURL("http://localhost/CsharpWeb/WebForm2.aspx")
        End Sub

        Sub TChart1_OnAfterDraw()

        End Sub
    </script>
</body>
  • Add in a new WebForm to your project and name it "WebForm2".
  • In the Page_Load event of WebForm2, add in the following code (C# example) and include the private field indicated:
    • private TeeChart.TChartClass tChart1 = new TeeChart.TChartClass();
private void Page_Load(object sender, System.EventArgs e) {
    tChart1.AddSeries(TeeChart.ESeriesClass.scBar);
    tChart1.Series(0).FillSampleValues(20);
    object stream = tChart1.Export.asNative.SaveToStream(true);
    Response.BinaryWrite((byte[])stream);
}

    TeeChart CAB files

    A CAB file version of TeeChart is included with the TeeChart installer for the registered version and available on the download page at the Steema web (www.steema.com) for the evaluation version. The CAB file is authenticoded. The CABfile callup definition in the html page would take the following form:

    Example

    <object
   id="Chart1"
   width="400"
   height="268"
   type="application/x-oleobject"
   hspace="0"
   vspace="0"
   classid="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258"
   CODEBASE="http://www.myweb.com/teechart2017.cab#Version=9,0,0,0">
</object>

    Changing the version number (teechart.cab#Version=9,0,0,0) allows you to manage which version the client machines should be running. The first time a client browser connects to the application it will download the CAB file. Thereafter it will check the local version against the version defined in the version line. Thus if you wish the client version to be upgraded, change the html page's version number to the server version number that you wish to make available and the client browser will download it if the local version is older.
    Example of use
    Setting teechart.cab#Version=9,0,0,1 in the <OBJECT> definition causes the browser to check the local version and download the CAB only if the local version is anterior. Assuming v2017.0.0.1 is downloaded the first time, the server based CAB is not called for download again until the version number in the codebase line is again incremented. Internet Explorer updates the registry with any differences between versions.

    Version Control

    To get two or more versions of TeeChart Pro ActiveX running side by side on your server, you should take into account the following:-

    The example given below is to concurrently display TeeChart Pro 6 and TeeChart Pro 2017 ASP Charts from your server.

    If you include the following line of code in your ASP scripts...

    Set Chart1 = CreateObject("TeeChart.TChart")

    ... it will create a Chart according to the current 'patron' of the HKEY_CLASSES_ROOT\TeeChart.TChart\Curver registry key, eg TeeChart 2017. However, if you already have pages containing TeeChart v6 ASP Charts on your website, they will be created serverside as v6 Charts and exported for importation to a v6 client (because the client is strictly version controlled via the <OBJECT> CLSID. This will generate incorrect functioning.

    To resolve the problem you should change all example scripts to be version 'tied':

    Eg.

    Set Chart1 = CreateObject("TeeChart.TChart.6")

    to create a v6 Chart.

    Set Chart1 = CreateObject("TeeChart.TChart.9")

    to create a v2017 Chart ('9' is an internal create version code for TeeChart v2017).

    The advantages in leaving CreateObject 'version open' is that it will always take the latest version. This is fine for closed scripts but not for those where a tee file is generated for export.

    Different instances of Internet Explorer should be able to use different versions of TeeChart at the same time without any problem.

    Printing from Internet Explorer

    Printing with later versions of Internet Explorer doesn't present any special issues. Earlier versions, (here notes refer to tests on v5) required the use of a TeeChart property. Internet Explorer version 5 creates a new instance of TeeChart at the moment of printing if printing a full browser page from IE5's 'File' menu, 'Print' option. By default that will cause TeeChart to lose its dynamic content, the data Series, causing the Chart to print as an empty Chart on the outputted page. This behaviour may be overidden by setting a TeeChart IE specific environment property, IEPrintWithPage. The property should be set to True for each Chart that is required to be printed with Series content.

    Example

    <script language="VBScript"><!--
Sub Window_Onload()
  '2 Charts in one browser page
  TChart1.Environment.IEPrintWithPage = True
  TChart2.Environment.IEPrintWithPage = True
End sub
--></script>

    TeeChart's own print methods may be used without any preparative steps. See Tutorial 14 for more information.

    More on Active Server Pages (ASP) and ASP/IIS Servers

    One of the areas for which we have received most enquiries has been relating to options for creation of ASP TeeChart applications. This section reviews the key options. It is assumed that Teechart Pro AX v5 is registered on the IIS server machine.

    An ASP page offers the possibility of full interactivity with the client browser and dynamic creation of both 'static' image (JPEG, PNG, GIF or PCX) charts and 'Live' (scrollable/zoomable, etc) TeeCharts. Exportation may take place via temporary files on the server or by directly streamed export to the browser.

    Creating a image Charting application with ASP/IIS servers

    The following ASP script shows a Chart page to the client, creates the Chart dynamically and sends the output as a JPEG file to the browser. Formatted Source

    <!--METADATA NAME="TeeChart Pro Activex control v2017" TYPE="TypeLib"
UUID="{5006E56D-FEDE-4C64-9CC2-78C320929406}"-->

<%
   'Send output to browser (and call RunChart method to build contents)
   Response.BinaryWrite(RunChart)
   Function RunChart()
    Dim img
    Dim Chart
        Set Chart = CreateObject("TeeChart.TChart")
        Chart.AddSeries(scBar)
    Chart.Series(0).Add 100, "Apples", RGB(255,0,0)
    Chart.Series(0).Add 300, "Pears", RGB(255,255,255)
    Chart.Series(0).Add 200, "Bananas", RGB(255,255,0)
    Chart.Export.asJPEG.CompressionQuality = 95
    Chart.Export.asJPEG.GrayScale = False
    Chart.Export.asJPEG.Height = 300
    Chart.Export.asJPEG.Width = 500
        img=Chart.Export.asJPEG.SaveToStream
        RunChart=img
        Set Chart=nothing
   End Function
%>

    Creating a Live Charting application with ASP/IIS servers

    The following script loads a Chart at the server and populates it with random data, loads a Chart on the client browser and runs a script to retrieve (import) the server generated Chart into the client Chart. Formatted Source

    <!--METADATA NAME="TeeChart Pro Activex control v2017" TYPE="TypeLib"
UUID="{5006E56D-FEDE-4C64-9CC2-78C320929406}"-->

<%
 ' Server side execution
 dim outputfile
 ' the following line may be replaced with your dynamic
 ' name creation code:
 outputfile = "http://localhost/filename.tee"
 ' The following line requires that you have the teechart.ocx
 ' file registered on the server
 ' The Server Chart is called Chart1
 Set Chart1 = CreateObject("TeeChart.TChart")
 Chart1.AddSeries(scLine)
 ' Use your methods eg. via DB to populate Chart or sample values
 ' for our example.
 Chart1.Series(0).FillSampleValues(10)

 ' Save the Chart as a .tee format file
 ' where the path locates to the same destination directory as
 ' the URL of the outputfile.
 Chart1.Export.SaveToFile "c:\inetpub\wwwroot\filename.tee"
%>
<HEAD></HEAD><BODY>
In the client section of the page we have added a TChart having the
TeeChart OBJECT defined as name TChart1.

<SCRIPT LANGUAGE=VBSCRIPT>
' This code is run at the browser asking the Server ASP code for the filename
' and loading that file into the Chart on the browser page
Sub FillChart()
  TChart1.Import.LoadFromURL("<%=outputfile %>")
End Sub

Sub TChart1_OnAfterDraw()
End Sub
</SCRIPT>

Call the FillChart script with a button or Window_Onload event:

<p><input type="button" value="Populate Chart" onclick="FillChart" name="cdmChart1"></p>

<OBJECT
   id="TChart1"
   width="400"
   height="268"
   type="application/x-oleobject"
   hspace="0"
   vspace="0"
   classid="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258"
   codebase="http://localhost/Teechart2017.cab#Version=9,0,0,0">
</OBJECT>

<p>TChart1 on the browser page uses the TeeChart ActiveX control, teechart2017.ocx or
teechart2017.cab loaded on the Client machine. This example uses the cabfile
definition to download TeeChart to the client machine if it doesn't already exist.</p>
</BODY></HTML>

    Streaming Charts directly to the browser

    TeeChart offers direct binary streaming of GIF, PNG and PCX Charts to the browser, in addition to the already existing streaming of JPEG and TEE files.
This technique offers dynamic creation and exportation of TeeCharts in a variety of image formats without the need to
create a temporary file on the server.

    The SaveToStream method is in fact applicable to all of the following formats:

  • BMP

    •

  • GIF

    •

  • HTML

    •

  • JPEG

    •

  • Metafile

    •

  • Native (TEE)

    •

  • PCX

    •

  • PNG

    •

  • Text

    •

  • XLS

    •

  • XML

    •
The SaveToStream method as applied to the Native (TEE) format takes a boolean argument which specifies if the series data is saved with the TEE file or not. With ASP, Binarywrite should be used to return the Chart to the browser.

    *Note A script containing Binarywrite should be separate and autonomous from the HTML page that calls it, in a similar way to the example in this tutorial (ie. 2 separate files).

    Example ExportChart.asp

    <!--METADATA NAME="TeeChart Pro Activex control v2017" TYPE="TypeLib"
UUID="{5006E56D-FEDE-4C64-9CC2-78C320929406}"-->
<%
' Meta data section above to permit use of TeeChart constants in script
Set Chart1 = CreateObject("TeeChart.TChart.8")

Chart1.Header.Text(0)="Performance"
Chart1.AddSeries(scCandle)
Chart1.Aspect.View3D=False

'use your methods eg via DB to populate Chart or...
Chart1.Series(0).FillSampleValues 9
Chart1.Height=500
Chart1.Width=1000

Response.BinaryWrite (Chart1.Export.asNative.SaveToStream( True ))
%>

That could be used in conjunction with an HTML page that may take the following form:

    <HTML>
<SCRIPT language=VBScript>

Sub Window_Onload()
 ' Use entire http path with LoadFromURL
 TChart1.Import.LoadFromURL("http://localhost/testscripts/ExportChart.asp")
End sub

Sub TChart1_OnAfterDraw()
End Sub

</SCRIPT>
<BODY>

<OBJECT
   id="TChart1"
   width="400"
   height="268"
   type="application/x-oleobject"
   hspace="0"
   vspace="0"
   classid="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258"
   codebase="http://locahost/testscripts/Teechart2017.cab#Version=9,0,0,0">
</OBJECT>

</BODY></HTML>

    If exporting to Jpeg file, the syntax in the script is nearly identical (in ExportChart.asp script):

    Response.BinaryWrite (Chart1.asJPEG.SaveToStream)

    ..and import to the HTML page would take the following form:

    <IMG SRC="http://your.Chartserver.com/scripts/ExportChart.asp">

    See the TeeChart ASP examples, included in the TeeChart Program Manager
group, for more examples of streaming TeeChart in ASP scripts.

    Native TeeChart ODBC access with ASP

    TeeChart Pro ActiveX supports ASP ODBC data connections via native TeeChart
properties and methods. ODBC data sources for use with ASP should be System DSNs. Formatted Source

    <HTML>
<HEAD><TITLE>TeeChart Native ODBC Page</TITLE></HEAD>
<BODY>
<p>This page connects a Server located Chart to an ODBC datasource and
exports/imports the Chart to the browser located TChart where it can
be zoomed/scrolled.</p>
<br>
<SCRIPT Language="VBScript" RUNAT=Server>
   SUB FillSave()
    Dim TChart1
    Set TChart1 = CreateObject("TeeChart.TChart")
    TChart1.AddSeries(1)
    TChart1.Series(0).ColorEachPoint = True
    ' Set NoPrompt mode to support ASP Connection Pooling
        TChart1.Environment.NoPromptDBConnect = True
        TChart1.Series(0).DataSource = "DSN=mySystemDSN;UID=Myname;PWD=myPassword; sql=SELECT * FROM myTable"
        TChart1.Series(0).LabelsSource = "MyNameColumn"
        TChart1.Series(0).YValues.ValueSource = "MyValuesColumn"
        TChart1.Series(0).CheckDatasource
       TChart1.Export.SaveToFile "c:\myChartdir\mychart.tee"
   END SUB
</SCRIPT>

<!-- Call the FillSave() function -->
<%FillSave%>
<object
   id="TeeCommander1"
   width="500"
   height="32"
   type="application/x-oleobject"
   hspace="0"
   vspace="0"
   classid="CLSID:34CE48EE-8287-4AF4-A28E-A12CA6597107">
</object>
<OBJECT classid="clsid:FCB4B50A-E3F1-4174-BD18-54C3B3287258"
  codebase="TeeChart2017.ocx#Version=9,0,0,0"
  id=TChart1
  TYPE="application/x-oleobject"
  width=500
  height=250
  align=center
  hspace=0
  vspace=0
  >
</OBJECT>
<SCRIPT Language="VBScript">
  TChart1.Import.LoadFromURL( "http://myServer/myChartDir/mychart.tee" )
  'where the above import folder directs to the save folder for the Chart
  TeeCommander1.Chart=TChart1
</SCRIPT>
</BODY>
</HTML>

    Native TeeChart ADO access with ASP

    The following example uses ADO to access the ODBC datasource. Formatted Source

    <% LANGUAGE="VBSCRIPT" %>
<html>

<head>
<script LANGUAGE="VBScript">
<!--
Sub window_onload()
  Chart.Import.LoadFromURL("http://localhost/testscripts/myChart.tee")
end sub
-->
</script>

<title>TeeChart ADO ODBC Access</title>
</head>
<p><script LANGUAGE="VBScript">
<!--
Sub Chart_OnDblClick()
  call Chart.ShowEditor()
end sub
-->
</script>
<OBJECT
   id="Chart"
   width="400"
   height="268"
   type="application/x-oleobject"
   hspace="0"
   vspace="0"
   classid="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258"
   codebase="http://localhost/Teechart2017.cab#Version=9,0,0,0">
</OBJECT>

</p>
<%
    Dim Chart
    Set Conn = Server.CreateObject("ADODB.Connection")
    Set RS = Server.CreateObject("ADODB.RecordSet")
    Conn.Open "TeeChart Pro System db"
        RS.Open "select * from [employee]", Conn, 1,1
    Set Chart = Server.CreateObject("TeeChart.TChart")
    Chart.AddSeries(0)
    Chart.AddSeries(0)
    Chart.Series(0).Color=&H00FF0000
    Chart.Series(0).Title="My data Series"
        Chart.Series(0).DataSource = RS
    Chart.Series(0).LabelsSource = "LastName"
    Chart.Series(0).YValues.ValueSource = "Salary"
    Chart.Series(0).CheckDataSource
    Conn.Close
    Chart.Series(1).Title="Average"
    Chart.Series(1).SetFunction(5)
    Chart.Series(1).Color=&H0040FF00
    Chart.Series(1).DataSource = "Series0"
    Chart.Series(1).FunctionType.Period = 0
    Chart.Left=5
    Chart.Top=5
    Chart.Export.SaveToFile("c:\inetpub\wwwroot\testscripts\MyChart.tee")
    Set Chart = Nothing
%>
</body>
</html>

    Naming TeeChart files in a multiuser environment

    Assuming you have written a process that creates TeeCharts dynamically at runtime
according to user demand, either .tee or jpeg files, it will be necessary to build in a
naming mechanism to allows new files to be created whilst others are in use. IIS caches
files for a limited time (up to 30 secs) preventing their being overwritten. There are
several options for dynamic naming of Charts, a couple are listed here:

    • Use the IP address of the caller's machine and/or Session id and timestamp as part of
    the filename.

    The session information of the caller's machine may be extracted from the user http
    request.
      •

      Applied example The example creates and exports a Chart as a .tee and .jpg file
  using dynamic naming, then imports both Charts to the Client browser page.

      <HTML>
<%
dim filePath
dim httpPath
dim outputTeefile
dim outputJpegfile

' where server filepath locates to the same as URL httpPath below it
filePath = "e:\inetpub\wwwroot\testscripts\"
httpPath = "http://localhost/testscripts/"
' Session and timestamping the exported Charts
outputTeefile = "Chart" & Session.Sessionid & Replace(Time,":","") & ".tee"
outputJpegfile = "Chart" & Session.Sessionid & Replace(Time,":","") & ".jpg"
Set Chart1 = CreateObject("TeeChart.TChart")
Chart1.AddSeries(1)
'use your methods eg via DB to populate Chart or...
Chart1.Series(0).FillSampleValues 20
' Saving as tee and JPEG file
Chart1.Export.asNative.SaveToFile filepath & outputTeefile, True
Chart1.Export.asJPEG.CompressionQuality = 100
Chart1.Export.asJPEG.Height = 290
Chart1.Export.asJPEG.Width = 450
Chart1.Export.asJPEG.SaveToFile filepath & outputJpegfile
%>
<HEAD></HEAD><BODY>
<p>In the client section of the page you can display JPEG or Live Charts.</p>

<SCRIPT LANGUAGE=VBSCRIPT>
Sub FillChart()
  ' Import tee file
  'msgbox "<%=httpPath%><%=outputTeefile %>"
  TChart1.Import.LoadFromURL("<%=httpPath%><%=outputTeefile %>")
End Sub
Sub TChart1_OnAfterDraw()
' The Live Chart brings advantage of being scriptable..eg:
TChart1.Canvas.Font.Color = RGB(240,240,50)
TChart1.Canvas.Font.Bold=True
If TChart1.SeriesCount > 0 then
 If TChart1.Series(0).Count > 0 then
   TChart1.Canvas.TextOut TChart1.Axis.Left.Position, _
                         TChart1.Axis.Top.Position - 18, _
                         "Max point: " & TChart1.Series(0).YValues.Maximum
 End if
End if
end sub
</SCRIPT>

<p>Here loading the Chart with a button (or could use IE Window_Onload event):</p>
<p><input type="button" value="Populate Chart" onclick="FillChart" name="cdmChart1"></p>

<OBJECT ID="TChart1" WIDTH=450 HEIGHT=290
 CLASSID="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258">
</OBJECT>
<!--Import JPEG file-->
<IMG SRC=<%=httpPath%><%=outputJpegfile%>></A>

</BODY></HTML>

    • Use the FileSystemObject to create a random name.
      <HTML>
<%
dim filePath
dim httpPath
dim outputTeefile
dim outputJpegfile

'====== below, temp filename
Dim TempFileName

Set fs = CreateObject("Scripting.FileSystemObject")
TempFileName = fs.GetTempName
'Remove extension
TempFileName = Trim(Left(TempFileName, Len(TempFileName) - 3))
'Place in required extensions
outputTeefile = TempFileName  & "tee"
outputJpegfile = TempFileName  & "jpg"
'====== above, temp filename

' where server filepath locates to the same as URL below
filePath = "d:\data\ChartFiles\"
httpPath = "http://myserver/ChartFiles/"

'===========
' Chart creation and save code
' see prior example
'===========
' ...etc.......

      •

    • ..or use the Windows registry to create, use and cycle a finite number of predefined
    filenames.
      •

    Use of TeeChart constants in ASP

    ASP won't inherently support TeeChart's constants unless you reference the Type Library (see below). If you don't reference the Type Library you need to use the integer equivalent of the constants when requiring to reference them.

    Example

    ' instead of:
TChart1.AddSeries(scBar)
' use...
TChart1.AddSeries(1)  'ESeriesClass in help

    All integer equivalents for TeeChart constants are listed in the TeeChart helpfile under their specific type name. A quick summary can be found by looking at the TeeChart constants files in the IIS examples folder.

You could include the constants files in your ASP scripts as an alternative to the technique outlined below.

  • VBScript constants: TChartConsts.vbs
    •

  • JScript constants: TChartConsts.js
    •

    TeeChart constants may be incorporated into a script by adding a reference at the beginning of the script (or global.asa file) to the TeeChart Type Library.

    Example - Script file with referenced constants

    <!--METADATA NAME="TeeChart Pro Activex control v2017" TYPE="TypeLib" UUID="{5006E56D-FEDE-4C64-9CC2-78C320929406}"-->
<%
' The metadata line above should appear on one line

' ************
' your asp script
' ************

%>


Tutorial 10 - Walk-through VBScript examples

TeeChart Pro Activex object definition

The basic Chart
Using MS FrontPage
Changing Chart parameters at runtime
Using TeeChart events

Using other TeeChart components

TeeChart Pro Activex object definition

The basic Chart

The following object code describes the Chart below. No changed design time parameters are saved with the Chart in this format other than Chart Width and Height.

<object
   id=Chart1
   width=500
   height=250
   type="application/x-oleobject"
   hspace=0
   vspace=0
   align=center
   classid="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258"
   CODEBASE="teechart2017.ocx#Version=9,0,0,0">
</object>

Please note that if the control is registered with the machine the codebase can be removed but that no minor version control will take place.

Using MS FrontPage

We can save design time changes using Microsoft's FrontPage. The Base64 definitions below have been created with Frontpage, after making a few changes to the TeeChart Title, plus enabling Panel Gradient.

*Version note
Please note a change between TeeChart versions. Up to v5.02 the Base64 output appeared as the following. This was generated via TeeChart's IPersistStream interface and was assigned as OBJECT data.

Format up to v5.02+

<OBJECT ID="TChart1" WIDTH=400 HEIGHT=251
 CLASSID="CLSID:B6C10489-FB89-11D4-93C9-006008A7EED4"
 data="DATA:application/x-oleobject;BASE64,iQTBton71BGTyQBg
 CKfu1FRQRjALVENoYXJ0Q2hhcnQABExlZnQCAANUb3ACAAVXaWR0aAOQAQZIZWl
 naHQD+wAQR3JhZGllbnQuVmlzaWJsZQkQVGl0bGUuRm9udC5Db2xvcgcHY2xCbG
 FjaxFUaXRsZS5Gb250LkhlaWdodAL0EFRpdGxlLkZvbnQuU3R5bGULBmZzQm9sZ
 AASVGl0bGUuVGV4dC5TdHJpbmdzAQYtVGVlQ2hhcnQgbW9kaWZpZWQgYW5kIHNh
 dmVkIGluIEJhc2U2NCBmb3JtYXQgBg53aXRoIEZyb250cGFnZQAAAAAAAAACAAA
 AAP////8="
</OBJECT>
Version 5.03 output has been modified to that of below. The change was made because support for TeeChart's IPersistStream interface was discontinued by Internet Explorer v5.5 sp2 and later versions. This caused access to saved Chart characteristics as 'data' to become unuseable. IE5.5+ supports the generation of the above saved information as PARAMs via the IPersistPropertyBag interface. As prior versions of Internet Explorer also support IPersistPropertyBag it is backwards compatible. The change will not adversely affect display of saved Charts in prior versions of IE.

Format TeeChart 5.03+

<OBJECT ID="TChart1" WIDTH=400 HEIGHT=251
 CLASSID="CLSID:B6C10489-FB89-11D4-93C9-006008A7EED4">
<param name="Base64" value="VFBGMAtUQ2hhcnRDaGFydAAETGVmdAIAA1RvcAIABVdpZHRoA5UBBkhlaWdodAP7ABBHcmFkaWVu
dC5WaXNpYmxlCRBUaXRsZS5Gb250LkNvbG9yBwdjbEJsYWNrEVRpdGxlLkZvbnQuSGVpZ2h0AvQQ
VGl0bGUuRm9udC5TdHlsZQsGZnNCb2xkABJUaXRsZS5UZXh0LlN0cmluZ3MBBi1UZWVDaGFydCBt
b2RpZmllZCBhbmQgc2F2ZWQgaW4gQmFzZTY0IGZvcm1hdCAGDndpdGggRnJvbnRwYWdlAAAAAAAA
AAIAAAAA/////w==">
</OBJECT>

Format TeeChart 2017

<object id=TChart1 classid="CLSID:FCB4B50A-E3F1-4174-BD18-54C3B3287258">
  <param name="Base64" value="VFBGMAtUQ2hhcnRDaGFydAAETGVmdAIAA1RvcAIABVdpZHRoA/QBBkhlaWdodAP6ABBHcmFkaWVu
dC5WaXNpYmxlCRJUaXRsZS5UZXh0LlN0cmluZ3MBBhJUZWVDaGFydCBQcm8gQVggdjcAAAAAAAAA
AgAAAAD/////">
</object>

Changing Chart parameters at runtime

Let's put a button on the page to run a VB script to put some data on the last Chart:

<SCRIPT LANGUAGE="VBScript">
    SUB FillChart
     TChart1.AddSeries( 1 )
     'Notice the replacement here of scBar Enum variable
     'by integer value 1. See 'Enum constants' in helpfile
     TChart1.Series(0).Clear
     TChart1.Series(0).Add 100, "Apples", RGB(255,0,0)
     TChart1.Series(0).Add 300, "Pears", RGB(0,255,0)
     TChart1.Series(0).Add 200, "Bananas", RGB(255,255,0)
    END SUB
</SCRIPT>
<INPUT TYPE=BUTTON VALUE="Example: Fill values using Visual Basic Script" NAME="cdmChart" onClick="FillChart">

Using VBScript we can change a variety of Chart parameters, for example:

<SCRIPT LANGUAGE="VBScript">
    SUB ChangeChart
     TChart1.Panel.Gradient.EndColor = RGB(0,0,193)
     TChart1.Header.Font.Color = RGB(255,255,255)
     TChart1.Series(0).VerticalAxis = 1
    END SUB
</SCRIPT>
<INPUT TYPE=BUTTON VALUE="Change Chart appearance" NAME="cdmChart2" onClick="ChangeChart">

Using TeeChart events

Event handling code should be placed before the Object triggering the event. In this example, again modifying the last Chart above, the code as reproduced below, is placed above the Chart in the HTML page. After the Series data is plotted the AfterDraw event is triggered and the Canvas code draws a rectangle and prints a message if there are more than 3 points in Series0.

<!--
Sub TChart1_OnAfterDraw()
 If TChart1.SeriesCount > 0 then
  If TChart1.Series(0).Count > 3 then
    TChart1.Canvas.Brush.Color = RGB(255,255,255)
    TChart1.Canvas.Rectangle 90, 90, 200, 120
    TChart1.Canvas.Font.Bold = True
    TChart1.Canvas.TextOut 100,100, (TChart1.Series(0).Count) + " data points"
  end if
 end if
end sub
-->

Use this button to refill the Chart and trigger the event.

Using other TeeChart components

The TeeChart Pro AX navigator/controlbar component, TeeCommander may be added to the HTML page and associated with a TeeChart:

The code may be placed in the Window_Onload event to automatically connect the Chart to TeeCommander at runtime. Example

  TeeCommander1.Chart=Chart2


Tutorial 11 - Zoom and Scroll

Zoom and Scroll are useful aids for focusing on specific data in a densely populated Chart. See the Visual Basic example code in folders 'Animated Zoom' and 'Scrolling'.

Contents

How to Zoom and Scroll using the Mouse

Zoom
Scroll

How to Zoom and Scroll by code

Zoom
Animated Zoom
Zoom events
Scroll

How to Zoom and Scroll using the Mouse

Zoom

To zoom in on a Chart, press the right mousebutton at the top left hand corner of the area you wish to zoom in on and, maintaining the mousebutton pressed, drag out the rectangle to the bottom righthand corner of the zoom area. release the mousebutton and the Chart will redraw the area selected.

To undo the zoom, press the left mousebutton anywhere on the Chart area and drag up and left with the mousebutton depressed. Release the button and the Chart will redraw to the originally defined Chart area.

Scroll

To scroll a Chart across, press the left mousebutton and, maintaining the mousebutton pressed, drag the mouse in the direction you wish to scroll the Chart. When you release the mousebutton the Chart will remain at the new location.

To undo the scroll, press the left mousebutton anywhere on the Chart area and drag up and left with the mousebutton depressed. Release the button and the Chart will redraw to the originally defined Chart area.

How to Zoom and Scroll by code

Zoom

Zoom is, by default, enabled. Use the Zoom.Enable property to disable zoom. See the Zoom interface for a full list of properties and methods associated with Zoom. To define a recatngular area over which to Zoom use the ZoomRect method.

Example

TChart1.Zoom.ZoomRect 100, 100, 120, 120

The ZoomRect co-ordinates are defined in screen pixels where 0,0 is the top left hand point of the Chart Panel.
The following code will zoom in on an area between the 2nd and 5th x-axis points, setting the y-axis to the scale of the maximum and minimum points of the entire Chart:

With TChart1
  .Zoom.ZoomRect .Axis.Bottom.CalcXPosValue(2), _
      .Axis.Left.CalcYPosValue(.Axis.Left.MaxYValue), _
      .Axis.Bottom.CalcXPosValue(5), _
      .Axis.Left.CalcYPosValue(.Axis.Left.MinYValue)
End With

Use 'Undo' to Zoom back out.

TChart1.Zoom.Undo

Animated Zoom

Animated Zoom offers stepped zooming. Instead of jumping from 'zoomed out' to 'zoomed in' in one step, you may set AnimatedZoom to enabled and define staggered steps for the zoom. Once AnimatedZoom is enabled you may zoom manually with the Mouse or by code.

Example

With TChart1
  .Zoom.Animated = True
  .Zoom.AnimatedSteps = 10
  .Zoom.ZoomRect .Axis.Bottom.CalcXPosValue(2), _
      .Axis.Left.CalcYPosValue(.Axis.Left.MaxYValue), _
      .Axis.Bottom.CalcXPosValue(5), _
      .Axis.Left.CalcYPosValue(.Axis.Left.MinYValue)
End With

Zoom events

Zooming in manually, or by code, will trigger the TChart.OnZoom event. Zooming out will trigger the TChart.UndoZoom event.

Scroll

Scroll is enabled in all directions as default. Use the Scroll.Enable property to disable Scroll or limit Scroll to one direction. The easiest way to scroll by code is to use the Axis Scroll method:

  TChart1.Axis.Bottom.Scroll 10, False
  'The value is the offset. 'False' refers to whether or not TeeChart
  'will allow scrolling beyond Series value limits.

Another way to control scroll is to define Axis maximum and minumum to scroll by code.

Example

With TChart1
  .Scroll.Enable = pmHorizontal 'permit manual scrolling horizontally only.
  .Axis.Bottom.Automatic = False
  .Axis.Bottom.Minimum = 2
  .Axis.Bottom.Maximum = 5
  .Repaint
End With

You could use scrollbars to change the Axis Minimum and Maximum values and thus control scrolling entirely by code.

Example

With TChart1
  .Scroll.Enable = pmHorizontal 'permit manual scrolling horizontally only.
  .Axis.Bottom.Automatic = False
  'limit display to 5 points onscreen
  .Axis.Bottom.Minimum = HScroll1.Value - 5
  .Axis.Bottom.Maximum = HScroll1.Value
  .Repaint
End With


Tutorial 12 - Exporting and Importing Charts

This tutorial is overviews exporting TeeCharts in various formats and importing TeeChart's own .tee format Chart templates. See the Visual Basic 6 "Import from file" example code in the Examples folder below your TeeChart installation folder.

Contents

Exporting Charts

Available formats
Example export

Exporting Images

BMP
JPEG
WMF & EMF
GIF
PNG
PCX
PDF
PostScript
Flex - Flash

Exporting data

Text, XML, HTML, XLS

TeeChart's 'Tee' template and data export import format

Tee files

Import

Importing Tee format files
Example import Tee file
Effect of changes made in importing Chart
SeriesTextSource, SeriesXMLSource and CrossTabSource
Other datasources

Exporting Charts

Available formats

Available Export formats. All formats may be copied to either a file or Clipboard or to a Stream.

Image formats

BMP | IBMPExport Class
JPEG | IJPEGExport Class
WMF & EMF | IMetafileExport Class
GIF | IGIFExport Class
PNG | IPNGExport Class
PCX | IPCXExport Class
PDF | IPDFExport Class
PostScript | IEPSExport Class

Data formats

Text | ITextExport Class
XML | IXMLExport Class
HTML | IHTMLExport Class
Excel | IXLSExport Class

Other formats
Tee format is a flexible format that stores Chart property information and, optionally, Chart data. Files are small (data dependent) and ideal for network use to update live client based Charts.

TEE (TeeChart) INativeExport Class

At runtime you can display the export dialogue by using the

ShowExport

method.

Example

Private Sub Command1_Click()
TChart1.Export.ShowExport
End Sub

Example export

Exporting to a file is reasonable straightforward, in most cases you just need to define the destination filename.

Example

With CommonDialog1
  .Filter = "Images (*.bmp)|*.bmp|Images(*.jpg)|*.jpg|Images(*.wmf)|*.wmf|Images(*.emf)|*.emf
|Images (*.gif)|*.gif|Images (*.png)|*.png|Images (*.pcx)|*.pcx|Images(*.eps)|*.eps|Images(*.pdf)|*.pdf"
  .ShowSave
  If .FileName <> "" Then
    Select Case .FilterIndex
    Case 1
    TChart1.Export.asBMP.SaveToFile (.FileName)
    Case 2
    TChart1.Export.asJPEG.SaveToFile (.FileName)
    Case 3
    TChart1.Export.asMetafile.SaveToFile (.FileName)
    Case 4
    TChart1.Export.asMetafile.Enhanced = True
    TChart1.Export.asMetafile.SaveToFile (.FileName)
    Case 5
    TChart1.Export.asGIF.SaveToFile (.FileName)
    Case 6
    TChart1.Export.asPNG.SaveToFile (.FileName)
    Case 7
    TChart1.Export.asPCX.SaveToFile (.FileName)
    Case 8
    TChart1.Export.asEPS.SaveToFile (.FileName)
    Case 9
    TChart1.Export.asPDF.SaveToFile (.FileName)
    End Select
  End If
End With

Exporting Images

BMP

BMP file export has additional parameters for colours and size.

Example

With TChart1.Export
    .asBMP.Colors = pfDevice
    .asBMP.Height = 400
    .asBMP.Monochrome = False
    .asBMP.Width = 500
    .asBMP.SaveToFile "C:\TestFiles\MyTeeChart.png"
End With

JPEG

JPEG file export now has parameters for speed and quality for both SaveToFile and SaveToStream.

Example

With TChart1.Export
    .asJPEG.CompressionQuality = 90
    .asJPEG.GrayScale = False
    .asJPEG.Height = 400
    .asJPEG.Width = 500
    .asJPEG.SaveToFile "C:\TestFiles\MyTeeChart.png"
End With

The CompressionQuality value (from 1 - 100) will make the file larger and thus slower to transmit across a network - quality is better though ! You will need to decide on the best balance to suit your application.

WMF & EMF

Enhanced Metafiles are simply created by setting "Enhanced" to True.

Example

With TChart1.Export
    .asMetafile.Enhanced = True
    .asMetafile.Height = 400
    .asMetafile.Width = 500
    .asMetafile.SaveToFile "C:\TestFiles\MyTeeChart.emf"
End With

GIF

GIF support is included with TeeChart courtesy of Anders Melander's Delphi GIFImage classes ((c) 1997-99 Anders Melander). Full documentation for the GIF classes are outside the scope of TeeChart's own documentation. Anders has donated GIFImage to the Jedi project who now co-ordinate documentation and support for it.

*Important Notice
TeeChart provides the means to create GIF Chart images but LZW compression has been disabled until the use and licensing of LZW has been completely clarified with Unisys. Unisys's position on LZW licensing has led us to the interim conclusion (unfortunately) that by not including LZW we protect ourselves and our customers against unexpected licensing battles with Unisys at a later stage. TeeChart continues to support GIF with RLE compression which is not subject to Unisys license. We will be happy to discuss the issue with any customer who feels that they need to use LZW and to make a joint approach to Unisys to clarify the license position.

The image format PNG is superior in many respects to GIF with LZW, particularly in the case of TeeChart where animations are not exported. We recommend the use of PNG where possible.

See Unisys and LZW for more information on use of GIF LZW encoded images.

Example

With TChart1.Export
    .asGIF.ColorReduction = rmWindows256
    .asGIF.Compression = gcRLE
    .asGIF.DitherMode = dmStucki
    .asGIF.Height = 400
    .asGIF.Width = 500
    .asGIF.SaveToFile "C:\TestFiles\MyTeeChart.png"
End With

PNG

PNG provides a compressed image format that is supported by all principle browsers.

Example

With TChart1.Export
    .asPNG.CompressionLevel = 10
    .asPNG.Height = 400
    .asPNG.Width = 500
    .asPNG.SaveToFile "C:\TestFiles\MyTeeChart.png"
End With

PCX

IPCXExport uses the PCX unit Copyright Software Matters Inc. 1999. Please see their web www.smatter.com for more information.

Example

With TChart1.Export
    .asPCX.Height = 400
    .asPCX.Width = 500
    .asPCX.SaveToFile "C:\TestFiles\MyTeeChart.pcx"
End With

PDF

Use IPDFExport to generate PDF (Adobe Portable Document Format) files from TChart controls. For more information about PDF format please see http://www.adobe.com/products/acrobat/adobepdf.html. PDF is copyright Adobe Systems Incorporated. All rights reserved.

Example

With TChart1.Export
    .asPDF.Height = 400
    .asPDF.Width = 500
    .asPDF.SaveToFile "C:\TestFiles\MyTeeChart.pdf"
End With

Flex - Flash

Use TeeChart's IFlexExport interface to generate Flash Charts. TeeChart's creates Flash (see About Flash at the Adobe Web) Charts via Adobe's Flex compiler (see About Flex at the Adobe Web). The Flex compiler is freely available for download from Adobe.

To use TeeChart with Flex:

  1. Install Flex to a folder on your machine and note the path to Flex's bin folder (eg. C:\Flex3\bin).
  2. Use either the Compile or CompileDeleteShow methods to create your Flash Chart.

Example

Private Sub Command1_Click()
  Dim tmpFolder
  Dim FlexBinFolder

  tmpFolder = "c:\tmp"
  FlexBinFolder = "c:\Flex3\bin"
  myWidth = 100
  myHeight= 200

  ' The following line creates the Flex code and compiles it to Flash
  ' and then shows the result on a browser page
  TChart1.Export.asFlex.CompileDeleteShow myWidth, myHeight, tmpFolder, _
     TChart1.Name, FlexBinFolder, True, True, True
End Sub

Some animations may be included with your Flash Chart. By adding a MarksTip tool to the Chart and activating the Expand animation when moving the mouseover the pointers on the Flash Chart, the pointers will expand and show a MarkToolTip.

Example

With TChart1
  .Series(0).FillSampleValues (8)
  .Legend.Visible = False
  .Tools.Add tcMarksTip
  .Tools.Items(0).asMarksTip.Series = TChart1.Series(0)

  .Animations.Add tcExpand
  .Animations.Items(0).asExpand.Target = cpSeriesPointer
  .Animations.Items(0).asExpand.Trigger = atMouseOver
End With

TeeChart used for Flash output is ideal to include a small, 'CompactChart' to accompany editorial written content but any size Chart may be produced by this technique.

Flex and Flash are copyrights Adobe Systems Incorporated. All rights reserved.

PostScript

Use IEPSExport to export TeeCharts to EPS (Encapsulated PostScript) format.

Example

With TChart1.Export
    .asEPS.Height = 400
    .asEPS.Width = 500
    .asEPS.SaveToFile "C:\TestFiles\MyTeeChart.eps"
End With

Exporting data

There are four Export formats for Series data:

Text | ITextExport Class
XML | IXMLExport Class
HTML | IHTMLExport Class
Excel | IXLSExport Class

The above components may be associated with a Chart Series from which they can export data as either File, Stream or to the Clipboard. The following example exports the data from a Chart Series to an HTML table:

With TChart1.Export
    .asHTML.IncludeHeader = True
    .asHTML.IncludeIndex = True
    .asHTML.IncludeLabels = True
    .asHTML.Series = 0
    .asHTML.SaveToFile "C:\TestFiles\MyTeeChart.htm"
End With

The output of the above with a random dataset is the following:

Index | Text | Series0
0 | MyLabel 0 | 1,953125
1 | MyLabel 1 | 70,5547511577606
2 | MyLabel 2 | 53,3424019813538
3 | MyLabel 3 | 57,9518616199493
4 | MyLabel 4 | 28,9562463760376
5 | MyLabel 5 | 30,1948010921478
6 | MyLabel 6 | 77,4740099906921
7 | MyLabel 7 | 1,4017641544342
8 | MyLabel 8 | 76,072359085083
9 | MyLabel 9 | 81,4490020275116
10 | MyLabel 10 | 70,9037899971008

TeeChart's 'Tee' template and data export/import format

Tee files

Tee files are TeeChart's own template format for saving Charts and their data. Modified Chart properties are saved with the template and reproduced when the template is imported to a new Chart.

Advantages:

  • Tee files are very small in size, in most cases that offers an advantage over pure graphics formats (Quicker).
  • The destination Chart for the template is 'live', it can be zoomed and scrolled and have its properties modified.
  • Data may optionally be included with the tee template according to your preference.

Tee files are particularly useful in distributed Charting applications and offer the possibility to offer Web browser OLE/ODBC applications where the OLE/ODBC DSN resides only at the server. See the Internet Applications tutorial.

Example

With CommonDialog1
    .Filter = "TeeFile (.tee)|*.tee"
    .ShowSave
    If .FileName <> "" Then
        TChart1.Export.asNative.SaveToFile .FileName, True
    End If
End With

Import

Importing Tee format files

Import a saved Tee file from a local file source or http data source.

Example Imports

Example

'import from file
With CommonDialog1
  .Filter = "Images (.tee)|*.tee"
  .ShowOpen
  If .filename <> "" Then
    TChart2.Import.LoadFromFile (.filename)
  End If
End With

'or
'URL..
TChart2.Import.LoadFromURL "http://mywebserver.domain/myteefile.tee"

'or
'Stream..
Dim MyStream As Variant
MyStream = TChart1.Export.asNative.SaveToStream(True)
TChart2.Import.LoadFromStream MyStream

Effect of changes made in importing Chart

As .tee files only save changes to the standard Chart definition, if the destination Chart includes property changes not touched upon with the Chart to be imported, the originals will carry through. An example would be a Chart Footer. If the .tee file has not had the Footer set and the destination Chart does have, then the Footer will show through the Chart after importation. That may be a desirable result. If you expect changes to be made to the importing Chart that could adversely affect the desired result after a Chart has been imported into it, then you can use the ClearChart method before importation.

Example

Dim MyStream As Variant
MyStream = TChart1.Export.asNative.SaveToStream(True)
TChart2.ClearChart
TChart2.Import.LoadFromStream MyStream

SeriesTextSource, SeriesXMLSource and CrossTabSource

Tee files may be imported from remote web sources via the LoadChartFromURL method. CSV data may be imported via the ISeriesTextSource component and XML data may be imported via the SeriesXMLSource component. The CrossTabSource component connects to any dataset and automatically creates series from database data, using Group and Label fields and formula (sum or count values). Please see the TeeChart's Additional palette components for more information.

Other datasources

For information about data import from other database information sources please see the Database Access tutorial.


Tutorial 13 - Custom drawing on the Chart Panel

TeeChart offers extensive custom drawing facilities via the Canvas object. With Canvas you may add shapes, lines and text anywhere on the Chart Panel and define their colours, pen and brush styles.

Contents

TeeChart Canvas

Drawing order
Ensuring that custom drawn items are saved to the Canvas
Drawing Lines
Canvas Pen and Brush
Adding 2D Shapes
Adding 3D Shapes
Adding text
Applied example

TeeChart Canvas

Drawing order

When using TeeChart's Canvas methods remember that drawing order is important. Drawing a Line on the Chart then adding Series data points will cause the Line to be overdrawn. You could put the Line in the Series BeforeDrawValues event for the Line to appear above the Chart grid and below the Series. You could place the Line code in the OnAfterDraw event for the Line to appear above the Series.

Event order, 4 principle Chart draw events

  • OnBeforeDrawChart event
  • OnBeforeDrawAxes event
  • OnBeforeDrawSeries event
  • OnAfterDraw event

Ensuring that custom drawn items are saved to the Canvas

If you do not place calls to Canvas draw code in one of the Chart events, custom drawing will not be saved to the Canvas permanently thus causing any addition to be lost when an application is minimised or another Window placed over it. Your code does not need to reside directly in the Chart events, user drawn items can be saved for the life of the Chart window if you place code in OnBeforeDrawSeries/OnAfterDraw to check for flags set by your runtime Draw methods and thus run your draw code when activity is flagged as true.

Drawing Lines

Let's add a Canvas Line:

Example

'Draw a Line diagonally from top left to bottom right
'in the Chart Area of a 2D Chart
With TChart1
  'Move the pointer to the top left Chart point
  .Canvas.MoveTo .Axis.Left.Position, .Axis.Top.Position
  'Draw the Line
  .Canvas.LineTo .Axis.Right.Position, .Axis.Bottom.Position
End With

On a 3D Chart the Axis positions are offset from the Chart area due to 3D orthogonal displacement. We can move the Line accordingly:

Example

'Draw a Line diagonally from top left to bottom right
'in the Chart Area of a 3D Chart
With TChart1
  'Move the pointer to the top left Chart point + adjust for 3D
  .Canvas.MoveTo .Axis.Left.Position + .Aspect.Width3D, .Axis.Top.Position - .Aspect.Height3D
  'Draw the Line + adjust for 3D
  .Canvas.LineTo .Axis.Right.Position + .Aspect.Width3D, .Axis.Bottom.Position - .Aspect.Height3D
End With

Canvas Pen and Brush

The Line above is drawn using the Pen and Brush defined for the last object drawn before the Line is drawn. That may or may not be the Pen you want. Change the Pen accordingly:

Example

'Define Pen and Brush before drawing the Line
With TChart1
  .Canvas.Pen.Color = vbBlue
  .Canvas.Pen.Width = 1
  .Canvas.Pen.Style = psDot 'Pen must be 1 to use Pen.Style
  .Canvas.Brush.Style = bsClear 'transparency
  .Canvas.MoveTo .Axis.Left.Position + .Aspect.Width3D, .Axis.Top.Position - .Aspect.Height3D
  .Canvas.LineTo .Axis.Right.Position + .Aspect.Width3D, .Axis.Bottom.Position - .Aspect.Height3D
End With

Adding 2D Shapes

Add Canvas Shapes in a similar manner to Canvas Lines. The following example adds a Rectangle in the centre of the Chart Area:

2D Chart
2D Charts only support 2D shapes.

Example

With TChart1
   'prepare Pen and Brush
   .Canvas.Pen.Color = vbBlue
   .Canvas.Pen.Width = 1
   .Canvas.Pen.Style = psDot
   .Canvas.Brush.Color = vbWhite
   .Canvas.Brush.Style = bsSolid
   .Canvas.Rectangle (.Axis.Left.Position + (.Axis.Right.Position - .Axis.Left.Position) / 3), _
                     (.Axis.Top.Position + (.Axis.Bottom.Position - .Axis.Top.Position) / 3), _
                     (.Axis.Left.Position + (2 * (.Axis.Right.Position - .Axis.Left.Position) / 3)), _
                     (.Axis.Top.Position + (2 * (.Axis.Bottom.Position - .Axis.Top.Position) / 3)) _

End With

3D Charts
On a 3D Chart you can move the Rectangle in a Z plane too. See the RectangleWithZ method. This example for an orthogonal or Nativemode/OpenGL Chart places the Rectangle on the Left Wall but displaces it halfway towards the rear of the Chart (towards the Back Wall).

With TChart1
   'prepare Pen and Brush
   .Canvas.Pen.Color = vbBlue
   .Canvas.Pen.Width = 1
   .Canvas.Pen.Style = psDot
   .Canvas.Brush.Color = vbWhite
   .Canvas.Brush.Style = bsSolid
   'Draw Rectangle with Z displacement
   .Canvas.RectangleWithZ .Axis.Left.Position, _
          .Axis.Top.Position, _
      .Axis.Left.Position + ((.Axis.Right.Position - .Axis.Left.Position) / 2), _
          .Axis.Top.Position + ((.Axis.Bottom.Position - .Axis.Top.Position) / 2), _
          .Aspect.Width3D / 2
End With

Adding 3D Shapes

You may add 3D shapes to 3D Charts. This example draws a Cube in the top, left quadrant of the Chart rectangle. The depth covers the area from the front of the Walls to the Back Wall. See the Cube method.

With TChart1
   'prepare Pen and Brush
   .Canvas.Pen.Color = vbBlue
   .Canvas.Pen.Width = 1
   .Canvas.Pen.Style = psDot
   .Canvas.Brush.Color = vbWhite
   .Canvas.Brush.Style = bsSolid
   'Draw Cube
   .Canvas.Cube .Axis.Left.Position, _
          .Axis.Left.Position + ((.Axis.Right.Position - .Axis.Left.Position) / 2), _
          .Axis.Top.Position, _
          .Axis.Top.Position + ((.Axis.Bottom.Position - .Axis.Top.Position) / 2), _
          0, .Aspect.Width3D, True
End With

Adding text

2D Text location
Add Text to the last Rectangle:

Example

With TChart1
   'prepare Pen and Brush
   .Canvas.Pen.Color = vbBlue
   .Canvas.Pen.Width = 1
   .Canvas.Pen.Style = psDot
   .Canvas.Brush.Color = vbWhite
   .Canvas.Brush.Style = bsSolid
   .Canvas.Rectangle (.Axis.Left.Position + (.Axis.Right.Position - .Axis.Left.Position) / 3), _
                     (.Axis.Top.Position + (.Axis.Bottom.Position - .Axis.Top.Position) / 3), _
                     (.Axis.Left.Position + (2 * (.Axis.Right.Position - .Axis.Left.Position) / 3)), _
                     (.Axis.Top.Position + (2 * (.Axis.Bottom.Position - .Axis.Top.Position) / 3)) _

   .Canvas.Font.Color = vbRed
   .Canvas.TextOut (.Axis.Left.Position + (.Axis.Right.Position - .Axis.Left.Position) / 3) + 5, _
                   (.Axis.Top.Position + (.Axis.Bottom.Position - .Axis.Top.Position) / 3) + 5, _
                   "My text"
End With

3D Text location
You can place Text in a differing 3D plane by using the TextOut3D method.

Example
 With TChart1
  .Canvas.Brush.Style = bsClear
  .Canvas.TextOut3D .Axis.Left.Position, .Axis.Top.Position, .Aspect.Width3D / 2, "Hello"
 End With

Applied example

This example takes the 3rd and 10th values of a Series, plots a Line between them and tells us the value of the first and Last point of the new Line and the difference between them:

Example

'First add some data to the empty Chart
With TChart1
  'Add and populate Series
  .AddSeries scLine
  .Series(0).FillSampleValues 20
End With

'You could put this code in the OnAfterDraw event
With TChart1
  If .SeriesCount > 0 Then
    If .Series(0).Count > 10 Then
      'Add some Shapes
      .Canvas.Pen.Color = vbBlue
      .Canvas.Pen.Width = 1
      .Canvas.Pen.Style = psDot
      .Canvas.Brush.Style = bsClear
      .Canvas.MoveTo .Axis.Bottom.CalcXPosValue(.Series(0).XValues.Value(3)), _
                     .Axis.Left.CalcYPosValue(.Series(0).YValues.Value(3))
      .Canvas.LineTo .Axis.Bottom.CalcXPosValue(.Series(0).XValues.Value(10)), _
                     .Axis.Left.CalcYPosValue(.Series(0).YValues.Value(10))
      .Canvas.Brush.Style = bsSolid
      .Canvas.TextOut .Axis.Bottom.CalcXPosValue(.Series(0).XValues.Value(3)), _
                      .Axis.Left.CalcYPosValue(.Series(0).YValues.Value(3)), _
                      "Point value: " + Str$(.Series(0).YValues.Value(3))
      .Canvas.TextOut .Axis.Bottom.CalcXPosValue(.Series(0).XValues.Value(10)), _
                      .Axis.Left.CalcYPosValue(.Series(0).YValues.Value(10)), _
                      "Point value: " + Str$(.Series(0).YValues.Value(10))
      .Canvas.TextOut .Axis.Bottom.CalcXPosValue(.Series(0).XValues.Value(10)), _
                      .Axis.Left.CalcYPosValue(.Series(0).YValues.Value(10)) + _
                      .Canvas.TextHeight("Any letter"), "Change is: " + _
                      Str$(.Series(0).YValues.Value(10) - .Series(0).YValues.Value(3))
    End If
  End If
End With
End Sub


Tutorial 14 - Printing Charts

Standard Printing

Simple Print command
Print Orientation
Print Preview
Print Detail
Greyscale printing

Extended Printing methods

PrintPartial
Printing multiple page Charts
Printing several Charts on one page
Mixing printed Chart output with other print output

Standard Printing

TeeChart Pro offers standard print methods to print the Onscreen Chart 'as is' to the Printer.

Simple Print command

To print a Chart use the PrintChart method. This will print the chart as it appears onscreen.

Example

TChart1.Printer.PrintChart

Print Orientation

The PrintPortrait and PrintLandscape methods allow you to print those orientations even if they are not defined as the default. The default orientation will take effect again after the prnt is complete. Default Orientation can be changed using the Orientation property. The Orientation method will not print for you. You must run Print afterwards.

Example

With TChart1.Printer
  .Orientation = poLandscape
  .PrintChart
End With

Print Preview

The PrintPreview window will show you how the Chart will appear when printed. You may modify print parameters in the Print Preview window. To call PrintPreview run:

TChart1.Printer.ShowPreview

Alternatively use the configurable PrintPreview of the TeePreviewer component (see Tutorial 17).

Print Detail

Print Detail is not to be confused with print resolution which is defined with your Printer setup in Windows' Print management. Print Detail defines the amount of TeeChart detail to be included in the printed Chart, its Axis scale detail, Gridline frequency, etc. The value range is a percentage from 0-100%.

Example

'this will use screen resolution
TChart1.Printer.Detail = 0
'this will use more printer resolution
TChart1.Printer.Detail = 100

Greyscale printing

When printing to Greyscale printers you should take care that the colours of the Chart are easily distinguishable when translated to shades of grey. To help, you could add Brush styles to the Chart Series to more easily distinguish Series when printed.

Extended Printing methods

PrintPartial

Use PrintPartial to send a Chart to the printer without ejecting the page. PrintPartial should be used with BeginDoc and EndDoc to start and end the Printer job. More than one Chart can be sent to the same page/printer job and user custom input can be included too.

Example

'Prints 2 Charts to a page
Private Sub Command2_Click()
  With TChart1.Printer
    .Orientation = poLandscape
    .BeginDoc
    .PrintPartial 0, 0, .PageWidth / 2, .PageHeight
  End With
  With TChart2.Printer
    .PrintPartial .PageWidth / 2, 0, .PageWidth, .PageHeight
    .EndDoc
  End With
End Sub

Printing multiple page Charts

For information about printing multipage Charts (where MaxPointsPerPage is less than the total point quantity) please see the Chart paging tutorial.

Print previewing several Charts on one page

The Print Preview panel now accepts more than one Chart (or TeePanel). Chart positions are controlled setting the PrintMargins property. Use the TeePreviewPanel1.Panels collection to manage the Charts on the Preview page.

  { change margins }
  Chart1.PrintProportional:=False;
  Chart2.PrintProportional:=False;

  Chart1.PrintMargins:=Rect(2,2,60,60);
  Chart2.PrintMargins:=Rect(60,60,2,2);

  { add to preview }
  TeePreviewPanel1.Panels.Add(Chart1);
  TeePreviewPanel1.Panels.Add(Chart1);

Only one Chart may be mousedrag moved on the Previewer at one viewing so you must disable the 1st Chart from view to enable drag repositioning of the 2nd Chart. The TeeChart demo project includes a page with the following code:

  With TeePreviewPanel1 do
  begin
    Panels.Clear;
    if CheckBox1.Checked then Panels.Add(FirstChart);
    if CheckBox2.Checked then Panels.Add(SecondChart);
    Repaint;
  end;

By selecting one or another of the 2 Checkboxes (when both are showing only the first Chart is moveable) you may reposition both the Charts on the page via mousedrag.

Mixing printed Chart output with other print output

Use the PrintPartialHandle method to mix TeeChart print output with non Chart printer output.

The following example takes the text from 2 Text boxes and prints them on a page with a TeeChart.

Private Sub Command1_Click()
Dim HWidth, HHeight, ChartLeft, ChartTop, ChartRight, ChartBottom ' Declare variables.
    On Error GoTo ErrorHandler  ' Set up error handler.
    Printer.Orientation = vbPRORPortrait
    'Scale & position text.
    HWidth = Printer.TextWidth(Text1.Text) / 2 ' Get half width.
    HHeight = Printer.TextHeight(Text1.Text) / 2   ' Get half height.
    Printer.CurrentX = Printer.ScaleWidth / 3 - HWidth
    Printer.CurrentY = Printer.ScaleHeight / 3 - HHeight
    Printer.Print Text1.Text ' Print 1st Text box
    With TChart1.Printer
      'Chart needs to orientated separately
      .Orientation = poPortrait
      'Set the chart position
      ChartLeft = .PageWidth / 3
      ChartTop = (.PageHeight / 3) + 30
      ChartRight = (.PageWidth / 3) * 2
      ChartBottom = (2 * (.PageHeight / 3)) - HHeight - 10
      'Attach the Chart output to the open print job
      .PrintPartialHandle Printer.hDC, ChartLeft, _
            ChartTop, ChartRight, ChartBottom
    End With
    Printer.CurrentY = 2 * Printer.ScaleHeight / 3 - HHeight
    Printer.CurrentX = Printer.ScaleWidth / 3 - HWidth
    Printer.Print Text2.Text ' Print 2nd Text box
    Printer.EndDoc  ' Printing is finished.
    Exit Sub

ErrorHandler:
    MsgBox "There was a problem printing to your printer."
    Exit Sub
End Sub


Tutorial 15 - MS VC++ Applications

Introduction

Quick start

Adding TeeChart to your Project
Naming the Chart
Adding data to the Chart
Upgrading from TeeChart v8

Working with TeeChart in VC++

Changing Chart properties at design time
TeeChart events
Coding TeeChart for runtime
How to apply TeeChart Online help to VC++
Notes on use of TeeChart in Windows 98
Notes on use of TeeChart in Visual Studio.NET
Constant defines
Notes about the TeeRect Structure
Applied examples

Using the additional TeeChart Controls in VC++

TeeCommander
TeeEditor
TeePreviewer
TeeListBox
TeePreviewPanel
ChartGrid and ChartGridNavigator
SeriesTextSource
SeriesXMLSource
CrossTabSource

Introduction

This tutorial focuses on some of the technical and syntactical issues for working with TeeChart and Microsoft's Visual C++. Most TeeChart documentation is written using Visual Basic examples but hopefully by the end of this tutorial you should find it easy enough to 'port' those examples and apply them to Visual C++ (of course VC++ then has a few tricks of its own !).

Applied examples in this tutorial originate with MFC in mind.

Quick start

Adding TeeChart to your Project

  • Use the 'New' option on the Developer Studio file menu and select 'MFC Application Wizard' from the Projects page. We'll start here by creating a Dialog based application, the Wizard leads you through the steps to create the application's project. On step 2 of the Wizard pages be sure to maintain ActiveX Controls selected (default).

  • When your project is created you may add the TeeChart control to the project. Select the 'Project' menu option from the IDE then 'Add To project' and 'Components and Controls'. Select TeeChart Pro Activex Control v2017 from the list of Registered ActiveX controls. After selecting the 'Insert' button you are offered a choice of which TeeChart classes you can add to the project. If in doubt as to what you will need, select them all. Close the 'Components and Controls gallery' dialog when finished. TeeChart classes now form a part of your project.

  • The next step is to add Teechart to the project's default Dialog box (for example). Go to the resources window of the project and select the Dialog folder. Within the folder you will see (normally) an 'About' dialogue and the 'Application' dialogue. Double click on the Dialog box to which you wish to add a TeeChart, that will open the Dialog box in its display format.

  • Right mouseclick on the Dialog box and select 'Insert Activex Control...' from the menu. Choose Teechart from the list of controls to place it on the Form from where you can drag it out to size.

  • You can now compile the application to see a Dialog box with an empty Chart. Please note that to save designtime Editor changes you should use the Chart Editor via the right mouseclick 'Properties' option not the right mouseclick 'TeeChart Pro Activex v2017 Object','Editor' option.

    • Naming the Chart

  • We must name the Chart to work with it. Open the ClassWizard and select the 'Member variables' page. Double-click on the Chart ID (probably IDC_TCHART1) to bring up the 'Member variable naming' screen. Add a name for this instance of TChart. In this example we will use 'm_Chart1'. Select 'OK' to exit.

    • Adding data to the Chart

  • Before we close this chapter we'll make the Chart show some data. We can add a data Series at design time but that is amply discussed in other tutorials so we'll do this at runtime here. Add a Button from the VC++ Component palette to the Dialog form. Right-click on the Button to confirm its ID and to add any desired Caption. Close the properties window for the Button and right-click anywhere on the Form to bring up the menu to select the ClassWizard. From within the 'Message maps' page select Class Name as the Dialog box, Object id as the Button id and then double-click on the Button's BN_CLICKED message to provoke the creation of a Function for the message. Select 'Edit code' to add/edit the function.

  • To display some data we need to add a Series and populate it.
    • void CMyDlg::OnButton1()
{
    //Add this include to the implementation file
    #include "Series.h"

    // Add a Bar Series, (constants are discussed later in the tutorial)
    m_Chart1.AddSeries(1);
    // Fill with random data
    m_Chart1.Series(0).FillSampleValues(10);
}

    Compile the project and select the button to populate a Bar Series on the Chart.

Upgrading from TeeChart v8

Please read the whole of this section before commencing to upgrade your VC++ project to TeeChart ActiveX Control v2017. The following describes manual steps and a semi-automated upgrade using the TeeChart Upgrade utility.

Manual upgrade

The differences between TeeChart Pro AX v8 and TeeChart Pro AX v2017 to be considered when upgrading v8 projects are as follows:

  • 1. A VC++ project lists all TeeChart interface ids in the .dsp project file. The interface ids have changed between v8 and v2017 so these ids must be modified. The TeeChart utilities folder contains a conversion document, guids.txt, for interface numbers. The document is used by the Upgrade utility tool when it upgrades the .dsp file.
  • 2. Ids for TeeChart placeable components are listed in the .dsw workspace file. The TeeChart utilities folder file, AllGuids.txt lists the conversions from v8->v2017 for these ids.
  • 3. The project .rc file contains the interface GUID for placed TeeChart components. The ids should be replaced with the Version 2017 equivalents as listed in the guids.txt file.
  • 4. Most Interfaces, interfaced as TeeChart classes by VC++ Class Wizard, have been updated in some way between v8 and v2017. The classes can be regenerated by re-adding the TeeChart control to your project. Please not that auto-generated pragma directives are not dependably regenerated by the Class Wizard. An option is to tackle any errors as they occur, often reported as duplicate definitions, by adding a pragma directive to the Class header file:
            #if _MSC_VER > 1000
        #pragma once
        #endif // _MSC_VER > 1000

            //prevents the following compile error type:
        tchart.h(29) : error C2017: 'CTChart' : 'class' type redefinition
    ..or add the directives to all header files before compiling the project as a preventative measure.
    ..or overwite the v8 class files with the TeeChart v2017 files created and stored in the New VC classes folder below the utilities folder.

Assisted upgrade

For most conventional project types the TeeChart Upgrade utility (accessible via the TeeChart Program Manager group) can do the majority of the routine work of the upgrade.

To use the upgrade tool, start it from the icon below the TeeChart Program Manager group. Select the VC++ tab and select the workspace you wish to upgrade.

  • The utility will do steps 1., 2. and 3. as described in the manual steps above. Though we recommend making a backup, the process will make a backup of changed files for you if you choose to accept the option.
  • The utility will do step 4. if you selected the checkbox option to copy over class files. You can do this step yourself. Whilst normally without issue, this step is only recommended to be made with the utility if your project has been built in a standard manner with the VC++ project wizard.

See the Upgrading from TeeChart v5 Word document, in the 'Docs' folder, for more information about upgrading projects from TeeChart v5.

Working with TeeChart in VC++

Changing Chart properties at design time

To change Chart properties at design time, right mouseclick on the Chart on the Form and select 'Properties' from the menu to display the properties window. Select the 2nd tab, TeeChart Pro Editor to display the Chart Editor. You can make changes to the Chart as described in previous tutorials.

*Note
Do not use the Chart Editor accessible via 'TeeChart Pro ActiveX Control Object' from the Mouse right Button menu when clicking on the Chart in a Form. If you Edit in this way and not via 'Properties' as described in the previous paragraph, modified properties are not permanently saved for runtime.

TeeChart events

Adding an event for the Chart on the Dialog Form is fairly straightforward. Right click on the Chart in the Form and select Events from the menu. Developer Studio offers you a list of TeeChart events. Select the event you wish to add from the list and the 'Add and Edit' button. This will add the handler and the function to the implementation file.

Coding TeeChart for runtime

MS VC++ adds the TeeChart classes to the project as per the steps outlined in Quick start. These can be viewed with the ClassView window. The Chart itself, here named as m_Chart1, can be accessed without further modification to the implementation file. To work with any other Class you will need to add it as an #include to the file. Take the following example, we are modifying the Chart Panel Gradient. We need to include the Classes for Panel and Gradient.

void CMyDlg::OnButton1()
{
    //Add includes
    #include "Panel.h"
    #include "Gradient.h"

    //Enable Panel Gradient
    m_Chart1.GetPanel().GetGradient().SetVisible(true);
}

Note the key difference to code described for Visual Basic in the online help file. VC++ requires the Get and Set of each property. In effect we are 'getting' each Class (Panel and Gradient) and 'setting' the property. The structure remains the same.

MS VC++ v7 makes coding considerably easier as you are now prompted with all properties and methods that relate to a Class as you type the code. You still need the header #include though.

How to apply TeeChart Online help to VC++

The Online help contains a listing of declarations of Classes, Properties, Methods, Constants and Events. These can be applied with reasonable uniformity to different programming environments. TeeChart coded examples, for all environments, can be found in the [image] Examples folder. The Online help also includes some examples, mostly written for Visual Basic. Due to space constraints there are far more examples in VB than VC++ but all principles used in VB can be applied in VC++. All new concepts are presented in the TeeChart AX Feature Demo accessible via the TeeChart Program Manager menu group. The following table translates some of the VB coded expressions used in the demo to VC++.

VB Expression

VC++ equivalent

Add method
TChart1.Series(0).Add 3, "Pears", vbRed

#include "series.h"

m_Chart1.Series(0).Add(3,"Pears",RGB(255,0,0));
Axis Title
TChart1.Axis.Left.Title.Caption="My left axis"

#include "axes.h"
#include "axis.h"
#include "axisTitle.h"

m_Chart1.GetAxis().GetLeft().GetTitle().SetCaption("My Left Axis");
Chart Title
With Chart1.Header.Text
    .Clear
    .Add("ACME Monthly Sales")
    .Add("Year: 2017")
End with

#include "Titles.h"
#include "Strings.h"

COleVariant var1(CString ("ACME Monthly Sales"));
COleVariant var2(CString ("Year: 2017"));
CTitles hd = m_Chart.GetHeader();
hd.GetText().Clear();
hd.GetText().Add(*(LPCVARIANT)var1);
hd.GetText().Add(*(LPCVARIANT)var2);

//if items (header lines) already in list (+ alternative COleVariant declare syntax)

m_Chart1.GetHeader().GetText().SetItem(0, COleVariant("ACME Monthly Sales"));
m_Chart1.GetHeader().GetText().SetItem(1, COleVariant("Year: 2017"));
Canvas draw
TChart1.Canvas.MoveTo(0,0)
TChart1.Canvas.LineTo(100,100)
TChart1.Canvas.TextOut(50,50,"My output text)

#include "Canvas.h"

m_Chart1.GetCanvas().MoveTo(0,0);
m_Chart1.GetCanvas().LineTo(100,100);
m_Chart1.GetCanvas().TextOut(50,50,"My output text");
OnGetAxisLabel event
'Add following text to Bottom Axis Labels
If aAxis = atBottom Then
  LabelText = "Period " + LabelText
End If

CString strLabel(*LabelText);
strLabel += " Period";
strLabel.SetSysString(LabelText);
OnGetNextAxisLabel event
If Axis = atBottom Then
   MoreLabels = True
   'Only label if following cases are true
   Select Case LabelIndex
      Case 0: LabelValue = 900
      Case 1: LabelValue = 5000
      Case 2: LabelValue = 10000
      Case Else: MoreLabels = False
   End Select
End If

{
  if (Axis == atLeft)
  {
    *MoreLabels = true;

    //Only label if following cases are true
    switch( LabelIndex )
    {
      case 0: *LabelValue = 900; break;
      case 2: *LabelValue = 5000; break;
      case 1: *LabelValue = 10000; break;
      default: *MoreLabels=false;
    }
  }
}
Outputting numeric information with Canvas TextOut
  Dim value1, value2, total As Integer

   value1 = 4
   value2 = 6
   total = value1 + value2

  TChart1.Canvas.TextOut 10, 10, total

  CString text;
  int value1,value2,total;

  value1 = 4;
  value2 = 6;

  total = value1+value2;

  text.Format(_T("Serie : %d"),total);

  m_Chart1.GetCanvas().TextOut(10,10,text));
Series as Datasource for Function
  ' Using Series datasource as an interface
  ' permits the input of Series from different
  ' Charts as Function datasource for a Chart Series

  With TChart1
    .AddSeries (scBar)
    .AddSeries (scLine)
    .Series(0).FillSampleValues 50

    .Series(1).SetFunction (tfAverage)

    '************************************
    .Series(1).DataSource = "Series0"

    'Or...

    .Series(1).DataSource = TChart1.Series(0)
    '************************************

    .Series(1).CheckDataSource
  End With

  VARIANT SourceSeries;

  m_Chart1.AddSeries(scBar);
  m_Chart1.AddSeries(scLine);
  m_Chart1.Series(0).FillSampleValues(50);

  m_Chart1.Series(1).SetFunction(tfAverage);

  //***********************************************************
  m_Chart1.Series(1).SetDataSource(COleVariant("Series0"));

  // Or....

  SourceSeries.vt=VT_DISPATCH;
  CSeries InputSeries=m_Chart1.Series(0);
  SourceSeries.pdispVal=InputSeries;

  m_Chart1.Series(1).SetDataSource(SourceSeries);
  //***********************************************************

  m_Chart1.Series(1).CheckDatasource(3);

Notes on use of TeeChart in Windows 98

An observation on VC++/Windows 98 behaviour: When TeeChart is added to a dialog form, VC++ creates an IDC constant for the Chart, eg. IDC_TCHART1 = 1000. If your project later calls upon Windows 98 to assign Hwnd handles for TeeChart upon request, eg. via the GetDlgItem method then, if several TeeCharts reside on a form, Windows 98 4 digit (decimal) dynamically allocated handles may coincide with values of the IDC constants assigned to the Charts. That shouldn't be a problem, however VC++ treats the original constants as duplicate Hwnd handles only in the case where duplicity occurs in the same live form, overriding the true Hwnd handle for a Chart and recognising the conflicting IDC_ constant, as a conflicting Hwnd handle. To avoid this behaviour set IDC_TCHART constants to five digit values, eg. 10001. The 4 digit handles returned by Windows will therefore not coincide with the Chart constant.

The above behaviour is only limited to Windows 95 and 98 platforms. WinNT and Win2000 use a higher address range for Hwnd handles.

Notes on use of TeeChart in Visual Studio.NET

Please note that when creating a VC++ 7.0 (or greater) MFC Application project the TeeChart AX v2017 classes (*.cpp) and header files (*.h) have to be added manually. All the files necessary can be found under the New VC classes folder below the utilities folder; these files should be copied to your project folder (using Windows Explorer) and then should be added in to the project (in Solution Explorer -> right click over "Source Files" & "Header Files" folders -> Add Existing Item...).

Constant defines

MS VC++ doesn't natively support import of TeeChart constants. You need to create you own defines file and #include it in your project. We offer a pre built defines file in the [image] Examples\Visual C++ folder. Including the file in your project will allow you to use constants by name as matching the Enum declarations in the Online help file.

Notes about the TeeRect Structure

Generation of the TeeRect structure, as with CalenderSeries may give the following error messages:

// method 'RectCell' not emitted because of invalid return type or
parameter type
And
// method 'SeriesRect' not emitted because of invalid return type or
parameter type

The automatic code generator fails to define the structure. You can do it manually:

typedef struct tagTeeRect
{
  long Left; // Left boundery value.
  long Top; // Top boundery value.
  long Right; // Right boundery value.
  long Bottom; // Bottom boundery value.
} TeeRect;

TeeRect CCalendarSeries::RectCell(long Column, long Row)
{
  static BYTE parms[] = VTS_I4 VTS_I4;
  VARIANT vtResult;
  InvokeHelper(0xb, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&vtResult, parms, Column, Row);
  return *(TeeRect*)vtResult.pvRecord;
}

TeeRect CCalendarSeries::GetSeriesRect()
{
  VARIANT vtResult;
  InvokeHelper(0xd, DISPATCH_PROPERTYGET, VT_VARIANT, (void*)&vtResult, NULL);
  return *(TeeRect*)vtResult.pvRecord;
}

The Calendar RectCell method should function correctly with the above definition for the structure. Thanks to Glyn Thomas for this contribution.

Applied examples

Canvas example
Canvas code placed in the OnAfterdraw event will draw after each Chart redraw thus allowing its use after Zoom or Scroll.

void CVCExampleDlg::OnOnAfterDrawTchart1()
{
    // Draw line to 5th point and label it
    if (m_Chart1.Series(0).GetCount() > 4)
    {
        CCanvas cv = m_Chart1.GetCanvas();
        CAxes ax = m_Chart1.GetAxis();

        //Setup pen and brush
        //See section Constant defines for
        // how to define bsClear
        cv.GetPen().SetColor(RGB(0,0,0));
        cv.GetBrush().SetStyle(bsClear);
        cv.TextOut(m_Chart1.Series(0).CalcXPos(5), m_Chart1.Series(0).CalcYPos(5), "HELLO");
        cv.MoveTo(ax.GetLeft().GetPosition(), ax.GetTop().GetPosition());
        cv.LineTo(m_Chart1.Series(0).CalcXPos(5), m_Chart1.Series(0).CalcYPos(5));
    }
}

ODBC example
This example connects to TeeChart ODBC test data and displays the Chart in the form of a Pie.

#include "series.h"
#include "valuelist.h"
#include "marks.h"

void CVCExampleDlg::OnButton5()
{
    // Add a Pie series and define the datasource
    m_Chart1.AddSeries(5);
    m_Chart1.Series(0).SetDataSource("DSN=TeeChart Pro Database; SQL=select * from employee");
    m_Chart1.Series(0).GetYValues().SetValueSource("SALARY");
        m_Chart1.Series(0).SetLabelsSource("LASTNAME");
    m_Chart1.Series(0).GetMarks().SetVisible(false);
}

Using the additional TeeChart Controls in VC++

TeeChart Pro AX v2017 includes several controls that may be added to a project to enhance runtime functionality of a Charting application.

TeeListBox | TeeEditor | TeePreviewer | TeeCommander | TeePreviewPanel | ChartGrid
TeeListBox | TeeEditor | TeePreviewer | TeeCommander | TeePreviewPanel | ChartGrid

ChartGridNavigator | ChartPageNavigator | ChartEditorPanel | SeriesTextSource | SeriesXMLSource | CrossTabSource
ChartGridNavigator | ChartPageNavigator | ChartEditorpanel | SeriesTextSource | SeriesXMLSource | CrossTabSource

The controls are separately listed in the Registered Controls list when using Project & Add to Project so you will need to select and add them individually.

TeeCommander

The ChartLink property connects the TeeCommander control bar to a TeeChart.

Example
m_Commander1.SetChartLink(m_Chart1.GetChartLink());

// Set the TeeCommander Editor to use TeeEditor1
// parameters when opening the Chart Editor
m_Commander1.SetEditorLink(m_TeeEditor1.GetEditorLink());
// Set the TeeCommander Print Previewer to use TeePreviewer1
// parameters when showing Print Preview.
m_Commander1.SetPreviewerLink(m_TeePreviewer1.GetPreviewerLink());

TeeEditor

The ChartLink property connects the TeeEditor control bar to a TeeChart.

Example
m_TeeEditor1.SetChartLink(m_Chart1.GetChartLink());

// Disable the 'Add Series' and 'Help' buttons on the Editor
m_TeeEditor1.GetOptions().SetAdd(false);
m_TeeEditor1.GetOptions().SetHelp(false);

TeePreviewer

Example
m_TeePreviewer1.SetChartLink(m_Chart1.GetChartLink());

TeeListBox

Example
m_TeeListBox1.SetChartLink(m_Chart1.GetChartLink());

TeePreviewPanel

Example
m_TeePreviewPanel1.SetChartLink(m_Chart1.GetChartLink());

ChartGrid and ChartGridNavigator

Example
m_ChartGrid1.SetChartLink(m_Chart1.GetChartLink());
m_ChartGridNavigator1.SetGridLink(m_ChartGrid1.GetGridLink());

SeriesTextSource

The SeriesTextSource component permits import of text file based data into a Chart Series.

Example
// See the TeeChart VC++ examples for a full working
// project with this code.
// Use the SeriesTextSourceComponent to import data
// from a text file.

// It's sensitive to decimal type in text so we do a check
// here on the machine locale.

VARIANT SeriesIndex;
LCID lcid;
CHAR lpszLang[2];

lcid=GetThreadLocale();
int rc = GetLocaleInfo(lcid, LOCALE_SDECIMAL, lpszLang, 2);

if (CString(&lpszLang[0]).Compare(CString(","))==0) {
        m_TextSource1.SetFilename("SurfaceDataComma.txt"); //use comma decimal separator
}
else {
        m_TextSource1.SetFilename("SurfaceDataPoint.txt"); //use point decimal separator
}

SeriesIndex.vt=VT_INT;
SeriesIndex.intVal= m_Chart1.AddSeries(scTriSurface);

// The following line only necessary if SeriesIndex as VT_INT.
m_TextSource1.SetChartLink(m_Chart1.GetChartLink());
m_TextSource1.SetSeries(SeriesIndex);
m_TextSource1.SetFieldSeparator(";");
m_TextSource1.AddField("x",1);
m_TextSource1.AddField("y",2);
m_TextSource1.AddField("z",3);
m_TextSource1.SetActive(true);

SeriesXMLSource

The SeriesTextSource is non-visible at run-time. It allows data to be brought in from XML files to specified Chart series. Use this compenent's methods and properties to define or modify the data's fields and field delimiters and to set the location of the XML file as a path, URL or stream.

Example
VARIANT SourceSeries;
m_Chart1.AddSeries(1);

SourceSeries.vt=VT_DISPATCH;
CSeries InputSeries=m_Chart1.Series(0);
SourceSeries.pdispVal=InputSeries;

m_SeriesXMLSource1.SetFileName("http://www.steema.com/SampleData.xml"); //This can also be a local file
m_SeriesXMLSource1.SetSeries(SourceSeries);
m_SeriesXMLSource1.SetSeriesNode("USA");
m_SeriesXMLSource1.SetValueSource("Bar");
m_SeriesXMLSource1.Open();

CrossTabSource

The CrossTabSource is non-visible at run-time. CrossTabSource component connects to any dataset and automatically creates series from database data, using Group and Label fields and formula (sum or count values).

Example
void CAXv6VC60MFCDlg::OnShowWindow(BOOL bShow, UINT nStatus)
{
    CDialog::OnShowWindow(bShow, nStatus);

    VARIANT SourceSeries;
    m_Chart1.AddSeries(1);

    SourceSeries.vt=VT_DISPATCH;
    CSeries InputSeries=m_Chart1.Series(0);
    SourceSeries.pdispVal=InputSeries;

    m_CrossTabSource1.SetSeries(SourceSeries);
    m_CrossTabSource1.SetGroupField("Terms");
    m_CrossTabSource1.SetLabelField("Paymtype");
    m_CrossTabSource1.SetValueField("Amntpaid");
    m_CrossTabSource1.SetDataSet(COleVariant("DSN=TeeChart Pro System db; SQL=select * from orders"));
    m_CrossTabSource1.SetActive(true);

    m_Chart1.RefreshData();
}

void CAXv6VC60MFCDlg::OnButton1()
{
    CString tmp;
    tmp = m_CrossTabSource1.GetGroupField();
    m_CrossTabSource1.SetGroupField(m_CrossTabSource1.GetLabelField());
    m_CrossTabSource1.SetLabelField(tmp);
    m_CrossTabSource1.SetActive(true);
    m_Chart1.RefreshData();
}


Tutorial 16 - Chart 3D and OpenGL

Chart display modes

(3D) Chart Editor page
2D Chart
3D Orthogonal Chart
3D "Native" Windows Chart
3D OpenGL Chart

Chart display modes

(3D) Chart Editor page

You may define the major 2D/3D display options with the Chart Editor at design time.

2D Chart

The 2D Chart may be selected at design time using the Chart Editor. Deselecting the 3D checkbox on the Editor page puts the Chart in 2D mode. At runtime you can change the Chart to 2D at any time with:

TChart1.Aspect.View3D = False

Working with the 2D Chart presents no special issues. All object co-ordinates are positions relative to the Chart panel or Chart rectangle, there is no need to make any allowance for 3D offset (see following sections).

3D Orthogonal Chart

3D Orthogonal mode is the default way to obtain 3D 'effect'. TeeChart draws depth effect at an orthogonal angle according to the Chart1.Aspect.Chart3DPercent property setting (also available at design time on the Chart Editor page). You cannot rotate a 3D Orthogonal Chart, the Bottom Axis is always horizontal.

When working with 3D orthogonal Charts you will need to take into account the Width3D and Height3D 3D offset when custom drawing to the Canvas. If you wish an item to be drawn to be flush with the Chart Backwall you should add the offset. See the following examples:

Example
Private Sub TChart1_OnAfterDraw()
'This example draws a diagonal line across the Chart
'flush to the Front of the Chart
With TChart1
  'Move the pointer to the top left Chart point
  .Canvas.MoveTo .Axis.Left.Position, .Axis.Top.Position
  'Draw the Line
  .Canvas.LineTo .Axis.Right.Position, .Axis.Bottom.Position
End With

'This example draws a diagonal line across the Chart
'flush to the Back of the Chart
With TChart1
  'Move the pointer to the top left Chart point
  .Canvas.MoveTo .Axis.Left.Position + .Aspect.Width3D, .Axis.Top.Position - .Aspect.Height3D
  'Draw the Line
  .Canvas.LineTo .Axis.Right.Position + .Aspect.Width3D, .Axis.Bottom.Position - .Aspect.Height3D
End With
End Sub

Use the Aspect interface when working with display properties for 3D Charts at runtime (*Note. Not all options are available for Orthogonal Charts).

3D "Native" Windows Chart

This 3D mode offers many of the display advantages obtainable with OpenGL but is faster. Native Windows mode 3D offers Chart rotation and elevation through 90º. You may Zoom in and out on the overall Chart (Zoom within the Chart is available too, see the Zoom/Scroll tutorial).

Select Native Windows mode 3D for TeeChart at design time by deselecting the Orthogonal checkbox on the 3D Editor page.

//Runtime
TChart1.Aspect.Orthogonal = False
In the Chart Editor, disactivating Orthogonal will simultaneously activate the slide bars for Elevation and Rotation allowing design time changes for these display properties.

For a closer look at the definition of the TeeChart Canvases look at the Custom drawing tutorial.

3D OpenGL Chart

You can convert the 3D Chart to an OpenGL Chart by using the OpenGL Boolean property found below the Aspect interface.

TChart1.Aspect.OpenGL.Active = True

You will see the Chart immediately convert to OpenGL at runtime.

Chart Editor and OpenGL

The Chart Editor will show the OpenGL Editor page when OpenGL is Active. If you require the OpenGL page to be permanently visible and for the application user to be able to activate/disactivate the Chart's OpenGL view mode, you should use the TeeEditor component which includes the page as default. If you are using the TeeEditor and require the OpenGL page to be hidden, you should set the TeeEditor.ShowPages.OpenGL property to false.

Example
' This example associates the TeeCommander Editor with
' a TeeEditor component to edit TChart1.
' The OpenGL page is hidden
TeeCommander1.Chart = TChart1
TeeCommander1.Editor = TeeEditor1
TeeEditor1.Chart = TChart1
TeeEditor1.ShowPages.OpenGL = False

OpenGL driver support

To use OpenGL support at designtime or runtime, be sure to have OpenGL enabled in the Windows machine. The standard Microsoft dll, OpenGL32.dll, is normally located in the Windows\System folder in the case of Windows95 and Windows98 and in the Winnt\System32 folder in the case of Windows NT.

Alternative OpenGL drivers are available form Silicon Graphics, www.sgi.com, both for NT and Windows 95/98.
Depending on your CPU and video hardware, it may be that the OpenGL dll's from Silicon Graphics are faster than the ones from Microsoft.

For a closer look at the definition of the TeeChart Canvases look at the Custom drawing tutorial.


Tutorial 17 - TeeChart's Additional palette components

Using the additional TeeChart Controls

Selecting and inserting the component
Associating the component with a TChart
TeeListBox
TeeEditor
TeePreviewer
TeeCommander
TeePreviewPanel
ChartGrid
ChartGridNavigator
ChartPageNavigator
ChartEditorPanel
SeriesTextSource
SeriesXMLSource
CrossTabSource

Using the additional TeeChart Controls

TeeChart Pro AX v5 includes several new controls that may be added to a project to enhance runtime functionality of a Charting application.

*Note For MS VC++ there are some points that you should take into account when using the additional TeeChart components. Please read the sections below as a general guide and look at the VC++ tutorial for specific VC++ related information.

TeeListBox | TeeEditor | TeePreviewer | TeeCommander | TeePreviewPanel | ChartGrid
TeeListBox | TeeEditor | TeePreviewer | TeeCommander | TeePreviewPanel | ChartGrid

ChartGridNavigator | ChartPageNavigator | ChartEditorPanel | SeriesTextSource | SeriesXMLSource | CrossTabSource
ChartGridNavigator | ChartPageNavigator | ChartEditorpanel | SeriesTextSource | SeriesXMLSource | CrossTabSource

Selecting and inserting the component

When you add TeeChart Pro to the Visual Basic Component panel the additional controls are automatically added too. For MS VC++, MS J++ and other development environments such as MS Access and Powerbuilder the controls are separately itemised in the Registered Controls list so you will need to select and add them individually.

Associating the component with a TChart

Associate TeeCommander and the other Non-Chart components with a TChart by using the Chart or ChartLink properties. The Chart property connects directly to the Chart interface which is supported with MS Visual Basic and Internet Explorer. For MS VC++, VJ++, Sybase Powerbuilder and other environments you will need to use the ChartLink property which returns the integer value of the Chart location.

Example

'Visual Basic
TeeCommander1.Chart = TChart1
or
TeeCommander1.ChartLink = TChart1.ChartLink

**** VC++ and other environments ****
eg. MS VC++
m_Commander1.SetChartLink(m_Chart1.GetChartLink());

Visible Components Example

VB Code:

Private Sub Form_Load()
With TChart1
    .AddSeries scArea
    .AddSeries scBar
    .AddSeries scLine
    .AddSeries scPoint
    For i = 0 To 3
        For j = 0 To 100
            .Series(i).AddXY j, Rnd(j) * 100, Chr(65 + j), clTeeColor
        Next j
        .Series(i).Marks.Visible = False
    Next i
    .Page.MaxPointsPerPage = 10
    .Legend.Visible = False
    .Aspect.View3D = True
    .Aspect.Orthogonal = True
    .Panel.Gradient.Visible = True
    .Panel.Gradient.StartColor = vbCyan
    .Panel.Gradient.EndColor = vbBlue
    .Tools.Add tcPageNumber
    With .Tools.Items(0).asPageNum
        .Position = ppLeftTop
        .Shape.Color = vbGreen
    End With
End With
ChartEditorPanel1.Chart = TChart1
ChartGrid1.Chart = TChart1
ChartGridNavigator1.Grid = ChartGrid1
ChartPageNavigator1.Chart = TChart1
TeeCommander1.Chart = TChart1
TeeListBox1.Chart = TChart1
TeePreviewPanel1.Chart = TChart1
End Sub

TeeListBox

TeeListBox shows a list of Series in the Chart at runtime. The ListBox may be used to offer the user limited customisation and display/hide of Chart Series.

TeeEditor

The TeeEditor component is non visible at runtime. Use the properties of this component to define the runtime Editor displayed to the user. Call the Editor with the ShowEditor method or associate the Editor with the TeeCommander bar to define characteristics of the Editor run from TeeCommander.

TeePreviewer

The TeePreviewer component is non visible at runtime. Use the properties of this component to define the runtime Previewer displayed to the user. Call the Previewer with the ShowPreviewer method or associate the Previewer with the TeeCommander bar to define characteristics of the Previewer run from TeeCommander.

TeeCommander

The TeeCommander bar allows navigation and parameter change control (via the Chart Editor) to be offered to users at runtime. Select the navigation buttons and with the left mouse button depressed, drag over the Chart panel to move the Chart. The EditorLink and PreviewerLink properties may be used to associate the runtime properties defined by those 2 components to the characteristics of the Chart Editor and Previwer when called from TeeCommander.

TeePreviewPanel

The TeePreviewPanel allows the visualisation of your Chart on a printed page at runtime. The Chart's margins can be dragged to the desired position.

ChartGrid

The ChartGrid shows the data in all the Chart's series. This data may be modified directly via Grid and the Grid itself may be associated with a ChartGridNavigator for easy reading.

ChartGridNavigator

The ChartGridNavigator, when associated with a ChartGrid via the Grid property, allows easy reading of and navigation through the ChartGrid.

ChartPageNavigator

The ChartPageNavigator facilitates the visualisation of a multi-page Chart when it is associated to one via the Chart property.

ChartEditorPanel

The ChartEditorPanel displays the Chart Editor at run-time in a Panel on your form or HTML page.

SeriesTextSource

The SeriesTextSource is non-visible at run-time. It allows data to be brought in from text files to specified Chart series. Use this compenent's methods and properties to define or modify the data's fields and field delimiters and to set the location of the textfile as a path, URL or stream.

Example

TChart1.AddSeries(scSurface)
With SeriesTextSource1

  ' AddField AName refers to the Series ValueList name
  ' The AIndex refers to the Column index of the text file
  ' beginning with Column 1
  .AddField "X", 1
  .AddField "Y", 2
  .AddField "Z", 3

  ' Check for locale decimal separator on PC
  ' and import formetted textfile accordingly
  If CInt("5,3") < CInt("5.3") Then
    .FileName = App.Path & "\SampleData.txt"
  Else
    .FileName = App.Path & "\SampleDataPoint.txt"
  End If

  .Series = TChart1.Series(0)

  ' or Series may be passed as Index but you would then
  ' have to set the Chart for the source
  'eg.
  ' .Chart = TChart1
  ' .Series = 0

  .Active = True
End With

SeriesXMLSource

The SeriesTextSource is non-visible at run-time. It allows data to be brought in from XML files to specified Chart series. Use this compenent's methods and properties to define or modify the data's fields and field delimiters and to set the location of the XML file as a path, URL or stream.

Example

Private Sub Form_Load()
TChart1.AddSeries scBar
With SeriesXMLSource1
    .FileName = "http://www.steema.com/SampleData.xml" 'This can also be a local file
    .Series = TChart1.Series(0)
    .SeriesNode = "USA"
    .ValueSource = "Bar"
    .Open
End With
End Sub

CrossTabSource

The CrossTabSource is non-visible at run-time. CrossTabSource component connects to any dataset and automatically creates series from database data, using Group and Label fields and formula (sum or count values).

Example

Private Sub Command1_Click()
Dim tmp As String
With CrossTabSource1
    tmp = .GroupField
    .GroupField = .LabelField
    .LabelField = tmp
    .Active = True
End With
TChart1.RefreshData
End Sub

Private Sub Form_Load()
TChart1.AddSeries scBar
With CrossTabSource1
    .Series = TChart1.Series(0)
    .GroupField = "Terms"
    .LabelField = "Paymtype"
    .ValueField = "Amntpaid"
    .DataSet = "DSN=TeeChart Pro System db; SQL=select * from orders"
    .Active = True
End With
TChart1.RefreshData
End Sub


Tutorial 18 - TeeChart runtime installation requirements

TeeChart runtime requirements

TeeChart runtime Files
Alternative 'small' TeeChart CAB file
Registry considerations
Customising TeeUser runtime help
OpenGL support

Running TeeChart Pro AX v8 and TeeChart Pro AX v2017 on the same machine.

TeeChart runtime requirements

This tutorial looks at some aspects of runtime installation for your TeeChart application.

TeeChart runtime Files

Which files to deliver with your TeeChart application depends on how the application is delivered. A standard Windows application differs from Web application delivery.

Windows application

  • teechart2017.ocx
    The file can be found in the TeeChart installation folder. It may be installed to any folder of your choice on the client (runtime) machine but must be registered (see section Registry considerations below).

  • teeuserx.hlp
    Optional Editor help support. The file can be found in Docs folder below the TeeChart installation folder. It may be installed to any folder of your choice on the client (runtime) machine but must be registered (see section Registry considerations below).
Web browser application
  • teechart2017.cab or teechart2017.ocx
    You may use either file for a Web application (both can be found in/below the TeeChart installation folder). teechart2017.cab is the compressed version of teechart2017.ocx, more suitable for transferring across the Internet where speed is a consideration. The CAB file is authenticoded. The files may be installed manually and manually registered (see section Registry considerations) in the client machine or loaded and registered dynamically using the HTML OBJECT Codebase link. See the Internet applications tutorial for more information about the use of CAB files and codebase. Where speed for downloading is a more critical element of your application you may wish to consider the use of the alternative 'cutdown functionality' version of TeeChart as listed in the Alternative 'small' TeeChart CAB file section.
  • teeuserx.hlp
    Optional Editor help support. The file can be found in Docs folder below the TeeChart installation folder. This file is not automatically registered when downloaded with an http connection so should be registered by alternative means (see section Registry considerations below).
* Use of PNG format export (all application types)
  • TeeChart Pro AX uses a dynamic link library, Lpng.dll to facilitate export to PNG format graphic files. The DLL is included with the TeeChart installer and is installed to the Windows\System[32] folder at installtime. If you require your redistributable application to export to PNG format files then you should include this DLL with your installer files. Lpng.dll is public domain. Version information may be found at http://www.libpng.org/.

Alternative 'small' TeeChart CAB file

An alternative TeeChart Cab file is supplied with the registered version. Located in the CAB files folder below the TeeChart installation folder, the file offers a limited functionality set of TeeChart, thus reducing the size of the Cab. The CAB file is authenticoded.

Functionality missing from the teesmall2017.cab file

  • No TeeChart Editor
  • No JPEG support
  • No Print Previewer
  • No About screen
  • No ODBC access
  • No OpenGL

The file may be made available in the same way as the teechart2017.cab file by using the HTML OBJECT Codebase parameter. See the Internet applications tutorial for more information about the use of CAB files and codebase.

Registry considerations

The TeeChart Pro ActiveX Control must be registered with the Windows registry to be useable. In most circumstances registration is achieved automatically but on some occasions (e.g. when creating your own application installation routines) it is necessary to manually register the Control. The TeeChart runtime Editor helpfile, teeuserx.hlp must also be registered to support help calls from the TeeChart Editor at runtime.

When creating an installer or installation routine for your compiled Charting applications you should include these aspects for TeeChart registration:

  • Register teechart2017.ocx
    To manually register teechart2017.ocx use Window's Regsvr32.exe.
    Example
    syntax:
  regsvr32.exe installdrive:\installfolder\teechart2017.ocx
eg.
  regsvr32 c:\Program files\MyChartApp\teechart2017.ocx
    • teeChart2017.ocx registry entries will be automatically added to several places of the Windows registry. There is no need to manually edit the registry.
  • Register teeuserx.hlp
    To register teesuerx.hlp you must create a routine, or add manually, to the Windows registry the following:
    Key:
  [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Help]
Entry:
  "teeuserx.hlp"="drive:\\installfolder\\installsubfolder"

Eg.
  "teeuserx.hlp"="c:\\Program files\\MyChartApp"

(Here assuming that teeuserx.hlp is installed in the
 c:\Program files\MyChartApp folder)

You may create a .reg registry file (which is ascii format)
by exporting the key from an existing registry entry.
The file may be used for direct importation to a client
installation.

    • When using the teechart2017.cab file and HTML OBJECT Codebase, TeeChart is automatically registered with the client Windows machine. If you wish to use teeuserx.hlp for web browser applications you must create your own routines for registering the helpfile. That could optionally involve the use of an exported registry file (normally ending with .reg) that automatically updates the register when executed (e.g. double-clicked).

Customising TeeUser runtime help

The source of the teeuser runtime Editor help, an rtf file, is saved in the Docs\Teeuser help source folder below the TeeChart Pro installation folder. The help source may be edited with a standard 32Bit Windows Help Editor or with Microsoft Word95 and compiled with Microsoft's 32bit Help Editor v4.00.0950+ or with Microsoft Word97/2000 and compiled with Microsoft's 32bit Help Editor v4.02.0060+. If edited with Word97 you cannot compile with the earlier version of Microsoft's 32bit Help Editor. The Help Editor is freely available from Microsoft.

When editing/compiling with a standard Help Editor or compiling with Microsoft's help compiler, open the teeuserx.hpj help project.

Replacing the default teeuserx.hlp file with the modified version and registering it in your client machines as per the instructions in the Registry considerations section will enable that help for use at runtime.
*Note
If using Word to edit the help .rtf file, be sure to edit page contents only and not to modify footnotes or hidden codes. To that measure, to avoid mistakes, it is advisable to work with the Word option, 'Show codes', activated.

OpenGL support

To use OpenGL support at designtime or runtime, be sure to have OpenGL enabled in the Windows machine. The standard Microsoft dll, OpenGL32.dll, is normally located in the Windows\System folder in the case of Windows95 and Windows98 and in the Winnt\System32 folder in the case of Windows NT.

Alternative OpenGL drivers are available form Silicon Graphics, www.sgi.com, both for NT and Windows 95/98.
Depending on your CPU and video hardware, it may be that the OpenGL dll's from Silicon Graphics are faster than the ones from Microsoft.

Running TeeChart Pro AX v8 and TeeChart Pro AX v2017 on the same machine.

You may use TeeChart Pro AX v8 and TeeChart Pro AX v2017 alongside each other on the same PC. Applications compiled with TeeChart Pro AX 8 or earlier will continue to use that version. Please take into account the following considerations:

  • If your application does not code in the TeeChart GUIDs (as would happen automatically when TeeChart is placed on a Form) and uses, rather, only CreateObject for Chart instances, then the CreateObject will create a TeeChart Pro AX v2017 Chart. As code is backwards compatible in all but a very few instances (see Tutorial 15, VC++ MS Applications for details) then the change in version will be transparent to the application user. Specific version creation may be fixed by naming the version during create (eg. to create a TeeChart v6 Chart in VBScript: CreateObject(TeeChart.TChart.6)

    • © 1998- Steema Software SL. All rights reserved.


Tutorial 19 - The TeeChart Tool Collection

Introduction

Series Tools

Cursor Tool
Design-time
Run-time

Drag Marks Tool
Design-time
Run-time

Drag Point Tool
Design-time
Run-time

Draw Line Tool
Design-time
Run-time

Extra Legend Tool
Design-time
Run-time

Gantt Drag Tool
Design-time
Run-time

Image Tool
Design-time
Run-time

Mark Tips Tool
Design-time
Run-time

Nearest Point Tool
Design-time
Run-time

Pie Slices Tool
Design-time
Run-time

Series Animation Tool
Design-time
Run-time

Axis Tools

Axis Arrows Tool
Design-time
Run-time

Color Band Tool
Design-time
Run-time

Color Line Tool
Design-time
Run-time

Grid Band Tool
Design-time
Run-time

Other Tools

3D Grid Transpose Tool
Design-time
Run-time

Annotation Tool
Design-time
Run-time

Page Number Tool
Design-time
Run-time

Rotate Tool
Design-time
Run-time

Introduction

This tutorial focuses on the TeeChart for .Net Tools, easily implemented units of code with which you or your application's users can add extra functionality to TeeCharts. There are ten new tools to deploy:

Series Tools

Cursor Tool
The Cursor Tool adds cursors to the Chart which can be associated with individual series or with the Chart as a whole. Cursors may be horizontal, vertical or both (crosshair).
Drag Marks Tool
The Drag Marks Tool allows the mousedrag of Marks for the selected Series.
Drag Point Tool
The Drag Marks Tool allows the mousedrag of Marks for the selected Series.
Draw Line Tool
The Draw Line Tool enables fully customisable lines to be drawn, selected, dragged and deleted on the Chart with the mouse.
Extra Legend Tool
The Extra Legend Tool allows a fully customisable extra legend to be drawn anywhere on the Chart canvas.
Gantt Drag Tool
The Gantt Drag Tool enables the bars of Gantt Series to be dragged and/or resized.
Image Tool
The Image Tool draws a picture (bitmap, jpeg, gif, png, pcx) behind a specified chart Series.
Mark Tips Tool
The Marks Tip tool is used to display default Hint windows when the mouse is over (or clicks) a Series point.
Nearest Point Tool
The Nearest Point Tool moves a marker to the point nearest to the cursor. The tool may be associated with a Series or applied globally to the Chart.
Pie Slices Tool
The Pie Slices Tool highlights the pie slice under the mouse either by drawing a border around it or by exploding it away from the rest of the Pie Series.
Series Animation Tool
The Series Animation Tool performs a growing animation of Series Points.

Axis Tools

Axis Arrows Tool
The Axis Arrow Tool displays configurable arrows at the beginning and end of axes. These arrows can be made to scroll the axes when clicked upon.
Color Band Tool
The Color Band Tool adds bands of configurable color to the interior region enclosed by the Chart axes. These bands may be set vertically or horizontally in line with the axis values.
Color Line Tool
The Color Line Tool adds colored lines to the Chart which can be set vertically or horizontally in line with the axis values.
Grid Band Tool
The Grid Band Tool adds fully configurable bands of color to the grids of a defined axis.

Other Tools

3D Grid Transpose Tool
The 3D Grid Transpose Tool exchanges X and Z coordinates to rotate a Grid-based series through 90 degrees.
Annotation Tool
The Annotation Tool allows text to be displayed on the Chart
Page Number Tool
The Page Number Tool displays a fully configurable text box containing a chosen page numbering system.
Rotate Tool
The Rotate Tool changes the elevation and rotation of charts when dragging the mouse over a chart.

At design-time these Tools are added by clicking on the Add... button of the Tools Tab within the Chart Editor:

At run-time only a few simple lines of code are necessary.

Annotation Tool

The Annotation Tool allows text to be displayed on the Chart.

Design-time

The Text of the Annotation Tool and the box it sits in can both be fully configured. The Options tab allows you to enter the text you wish and to specify its alignment and the cursor type that appear when the mouse is over the Tool. The Position tab specifies the default or custom position of the Annotation Tool. The Callout tab defines the Annotation Tool's Callout object which is used to draw a line from the annotation to any position in the chart. The Format tab configures the text box, allowing you to change its colour, frame, pattern, bevel, size, roundness and transparency. The Text tab enables the setting of the text font, colour, outline and spacing and also the colour and size of the text shadow. The Gradient tab configures the properties of the text-box gradient while the Shadow tab configures the properties of the text-box shadow.

Run-time

Adding an Annotation Tool at runtime is a straightforward operation, as can be seen in the example below:

With TChart1
    .Tools.Add tcAnnotate
    With .Tools.Items(0)
        .Active = True
        With .asAnnotation
          .Position = ppLeftTop
          .Shape.ShapeStyle = fosRoundRectangle
          .Shape.Font.Color = vbCyan
          .Text = "My Chart text"
        End with
    End With
End With

Axis Arrows Tool

The Axis Arrow Tool displays configurable arrows at the beginning and end of axes. These arrows can be made to scroll the axes when clicked upon.

Design-time

Once you have added an Arrow Tool a number of options become open to you. Axis enables to to select the axis (top, bottom, left, right or custom) to which you want to associate the Axis Tool. You may add more than one Axis Tool and associate each one with different axes. Border allows you to configure the style, colour, width and visibility of the pen outlining the arrow shape while Pattern allows you to configure the body of the arrow, it's colour, pattern or fill-image. Length descibes the length of the arrow in pixels, Position defines whether the arrows are drawn on the End, Start or at Both ends of the axis while Scroll defines the percentage of the axis length by which the axis will scroll when the arrows are clicked. Inverted Scroll will change the scroll direction.

Run-time

Adding an Axis Arrow Tool at runtime is a straightforward operation, as can be seen in the example below. Please note that the 3 in .Axis refers to the right axis; 0 refers to the bottom axis, 1 to the top axis, 2 to the left axis and 4 would refer to the first Custom axis (Custom 0), 5 to the second (Custom 1) etc.

Example

With TChart1
    .Tools.Add tcAxisArrow
    With .Tools.Items(0)
        .Active = True
        With .asAxisArrow
          .Axis = 3
          .Brush.Color = vbCyan
          .Length = 20
          .Pen.Color = vbRed
          .Pen.Width = 2
          .Position = aaBoth
          .ScrollPercent = 20
        End with
    End With
End With

Color Band Tool

The Color Band Tool adds bands of configurable color to the interior region enclosed by the Chart axes. These bands may be set vertically or horizontally in line with the axis values.

Design-time

There are a number of options to be able to configure the Color Band Tool once it's been added to your chart. Axis enables to to select the axis (top, bottom, left, right or custom) to which you want to associate the Color Band. Border allows you to configure the style, colour, width and visibility of the pen outlining the Color Band while Pattern allows you to configure the body of the Color Band, the pattern and its colour or fill-image. Gradient defines the visibility, direction and start, middle and end colours of the Color Band Gradient while Color, in the absence of a gradient or an image, defines the colour. Start value sets the start value on the specified axis from which the Color Band Tool will begin and End value sets the end value. Transparency is a value from 0 to 100 which sets the transparency of the Color Band Tool while Draw Behind enables/disables the drawing of it behind the Chart series.

Run-time

Adding an Color Band Tool at runtime is a straightforward operation, as can be seen in the example below:

Example
The Color Band Tool is very useful for highlighting a specific set of values within your series. In this example we are using a Color Band Tool which extends between the YValues of 20 and 60 and whose transparency can be altered by the Scroll Bar. Color Bands can be drawn in front of or behind your TeeChart series.

Private Sub Check1_Click()
  TChart1.Tools.Items(0).asColorband.DrawBehind = Check1.Value
End Sub

Private Sub Form_Load()
  With TChart1
    .Aspect.View3D = False
    .Panel.Gradient.Visible = True
    .Panel.Gradient.MidColor = vbGray
    .AddSeries scArea
    .Series(0).asArea.LinePen.Color = vbBlue
    For i = 0 To 10
        .Series(0).AddXY i, Rnd(i) * 100, "", clTeeColor
    Next i
    .Tools.Add tcColorband
    .Tools.Items(0).Active = True
    With .Tools.Items(0).asColorband
      .Axis = 0
      .Transparency = 50
      .EndValue = 60
      .StartValue = 20
      .DrawBehind = False
    End With
    End With
    Check1.Caption = "Draw Behind"
    Check1.Value = 0
    HScroll1.Min = 0
    HScroll1.Max = 100
    HScroll1.Value = 50
End Sub

Private Sub HScroll1_Change()
  TChart1.Tools.Items(0).asColorband.Transparency = HScroll1.Value
End Sub

Private Sub HScroll1_Scroll()
  HScroll1_Change
End Sub

Color Line Tool

The Color Line Tool adds colored lines to the Chart which can be set vertically or horizontally in line with the axis values.

Design-time

ColorLines can be associated with a specific Axis at a specific series Value while the style, colour, width and visibility of the ColorLine can be configured with Border. The Value Tab defines the custom and default Color Line Tool postions and the Options Tab specifies the ColorLine Tool options.

Run-time

Adding an Color Line Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcColorLine
    With .Tools.Items(0)
        .Active = True
        With .asColorLine
          .AllowDrag = True
          .Axis = 2
          .Pen.Color = vbBlue
          .Value = 100
        End with
    End With
End With

Cursor Tool

The Cursor Tool adds cursors to the Chart which can be associated with individual series or with the Chart as a whole. Cursors may be horizontal, vertical or both (crosshair).

Design-time

Once added, Cursor tools may or may not be associated with a Chart Series and may be configured in Style as being horizontal, vertical or both. If a Cursor Tool is associated with a series then it can be set to Snap to the series YValues as the cursor is moved. Follow Mouse causes the Cursor Tool to move with the mouse while Pen configures the colour, width, style and visibility of the Cursor Tool lines themselves.

Run-time

Adding a Cursor Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcCursor
    With .Tools.Items(0)
        .Active = True
        With .asTeeCursor
          .FollowMouse = True
          .Series = 0
          .Style = cssBoth
          .XValue = 4
          .YValue = 100
        End with
    End With
End With

Drag Marks Tool

The Drag Marks Tool allows the mousedrag of Marks for the selected Series.

Design-time

The Drag Marks Tool can be set to a specific Series or call be left associated with all Chart series. Reset Positions returns all moved marks back to their original default positions.

Run-time

Adding a Drag Marks Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcDragMarks
    With .Tools.Items(0)
        .Active = True
        .asDragMark.Series = 0
    End With
End With

Drag Point Tool

The Drag Point Tool allows the mousedrag of Series points for the selected or all Series.

Design-time

The Drag Point Tool can be set to a specific Series or call be left associated with all Chart series. Drag Style determineswhether points can be dragged along the x axis, along the y axis or along both.

Run-time

Adding a Drag Point Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

Draw Line Tool

The Draw Line Tool enables fully customisable lines to be drawn, selected, dragged and deleted on the Chart with the mouse.

Design-time

The Draw Line Tool can be set to a specific Series or call be left associated with none of the Chart series and can also be set, via Mouse Button, to a specific mouse button. Pen configures the colour, width, style and visiblity of the Lines themselves while Enable Drawing and Enable Select respectively enable/disable the drawing and selection of the Lines.

Run-time

Adding a Draw Line Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcDrawLine
    With .Tools.Items(0)
        .Active = True
        With .asDrawLine
          .Button = mbLeft
          .EnableDraw = True
          .EnableSelect = True
          .Series = 0
          .Pen.Color = vbCyan
        End with
    End With
End With

Extra Legend Tool

The Extra Legend Tool allows a fully customisable extra legend to be drawn anywhere on the Chart canvas.

Design-time

The Extra Legend Tool has to set to a specific Series for it to appear. The Edit Legend button gives access to a Legend Editor which allows the Extra Legend's Style, Position, Symbols, Format, Text, Gradient and Shadow to be configured.

Run-time

Adding a Extra Legend Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

Private Sub Form_Load()
With TChart1
    .AddSeries scBar
    .Series(0).FillSampleValues 6
    .AddSeries scBar
    .Series(1).FillSampleValues 6
    .Legend.LegendStyle = lsValues
    .Environment.InternalRepaint
    .Tools.Add tcExtraLegend
    With .Tools.Items(0).asExtraLegend
        .Series = TChart1.Series(1)
        .Legend.CustomPosition = True
        .Legend.Left = TChart1.Legend.ShapeBounds.Left
        .Legend.Top = TChart1.Legend.ShapeBounds.Bottom + 10
    End With
End With
End Sub

Gantt Drag Tool

The Gantt Drag Tool enables the bars of Gantt Series to be dragged and/or resized.

Design-time

The Gantt Drag Tool has to set to a specific Gantt Series for it to appear. Pixel resize tolerance specifies the minimum number a pixels a Gantt bar will be moved/resized, Allow Drag enables/disables the dragging of Gantt bars, Allow Resize enables/disables the resizing of Gantt bars while Cursor sets the mouse cursor that will appear during the respective operations.

Run-time

Adding a Extra Legend Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

Private Sub Form_Load()
TChart1.Aspect.View3D = False
TChart1.AddSeries scGantt
TChart1.Series(0).XValues.Order = loNone

With TChart1.Series(0)
    .asGantt.AddGantt DateSerial(2017, 4, 1), DateSerial(2017, 4, 10), 0, "A"
    .asGantt.AddGantt DateSerial(2017, 4, 5), DateSerial(2017, 4, 15), 1, "B"
    .asGantt.AddGantt DateSerial(2017, 4, 2), DateSerial(2017, 4, 8), 2, "C"
    .asGantt.AddGantt DateSerial(2017, 4, 9), DateSerial(2017, 4, 21), 3, "D"
    .Marks.Visible = True
    .Marks.ShadowSize = 0
    .Marks.Gradient.Visible = True
End With

TChart1.Axis.Bottom.SetMinMax DateSerial(2017, 4, 1), DateSerial(2017, 5, 1)
TChart1.Axis.Left.SetMinMax -2, 5
TChart1.Axis.Left.GridCentered = False
TChart1.Zoom.Enable = False
TChart1.Axis.Bottom.Increment = TChart1.GetDateTimeStep(dtOneDay)
TChart1.Axis.Bottom.Labels.Angle = 90
TChart1.Axis.Bottom.Labels.DateTimeFormat = "dd-mmm"
TChart1.Tools.Add tcGantt
TChart1.Tools.Items(0).asGantt.Series = TChart1.Series(0)
TChart1.Tools.Items(0).Active = True
End Sub

Private Sub TChart1_OnGanttToolDragBar(ByVal Tool As Long, ByVal GanttBar As Long)
With TChart1.Tools.Items(0).asGantt.Gantt
    Label1.Caption = FormatDateTime(.StartValues.Value(GanttBar)) + " - " + _
                    FormatDateTime(.EndValues.Value(GanttBar))
End With
End Sub

Private Sub TChart1_OnGanttToolResizeBar(ByVal Tool As Long, ByVal GanttBar As Long, ByVal BarPart As TeeChart.EGanttToolPartBar)
With TChart1.Tools.Items(0).asGantt.Gantt
    Label1.Caption = FormatDateTime(.StartValues.Value(GanttBar)) + " - " + _
                    FormatDateTime(.EndValues.Value(GanttBar))
End With
End Sub

Private Sub TChart1_OnGetSeriesMark(ByVal SeriesIndex As Long, ByVal ValueIndex As Long, MarkText As String)
Select Case ValueIndex
    Case 0: MarkText = "John"
    Case 1: MarkText = "Ann"
    Case 2: MarkText = "David"
    Case 3: MarkText = "Carol"
End Select
End Sub

Private Sub TChart1_OnMouseUp(ByVal Button As TeeChart.EMouseButton, ByVal Shift As TeeChart.EShiftState, ByVal x As Long, ByVal y As Long)
    Label1.Caption = ""
End Sub

Grid Band Tool

The Grid Band Tool adds fully configurable bands of color to the grids of a defined axis.

Design-time

The Grid Band Tool has to be associated with a specified Axis. Band 1 and Band 2 define the Brush characteristics for the the two bands, while Back defines the back color which shows through if the Band has a patterned Brush. Transparency sets the transparency level for each respective Band.

Run-time

Adding an Grid Band Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

Private Sub Form_Load()
With TChart1
    .AddSeries scBar
    .Series(0).FillSampleValues 6

    .Tools.Add tcGridBand
    With .Tools.Items(0).asGridBand
        .Axis = TChart1.Axis.Left
        .Band1.Color = vbGreen
        .Band2.Color = vbBlue
    End With
End With
End Sub

Grid Transpose Tool

The 3D Grid Transpose Tool exchanges X and Z coordinates to rotate a Grid-based series through 90 degrees.

Design-time

The 3D Grid Transpose Tool has to be associated with a specified Grid 3D Series. Transpose now will perform the Transpose operation at design time.

Run-time

Adding an Grid Transpose Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

Private Sub Command1_Click()
With TChart1.Tools.Items(0).asGridTranspose
        .Transpose
    End With
End Sub

Private Sub Form_Load()
With TChart1
    .AddSeries scSurface
    .Series(0).FillSampleValues 20

    .Tools.Add tcGridTranspose
    With .Tools.Items(0).asGridTranspose
        .Series = TChart1.Series(0)
    End With
End With
End Sub

Image Tool

The Image Tool draws a picture (bitmap, jpeg, gif, pcx) behind a specified chart Series.

Design-time

The Image Tool can be associated with a specific Series or can be left at default associated with none of the Chart series. Using Image one can browse for or clear images of all formats.

Run-time

Adding an Image Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcChartImage
    With .Tools.Items(0)
        .Active = True
        .asChartImage.ImageLoad "C:\TestImages\MyImage.jpg"
    End With
End With

Mark Tips Tool

The Marks Tip tool is used to display default Hint windows when the mouse is over (or clicks) a Series point.

Design-time

The Mark Tips Tool can be associated with a specific Series or can be left at default associated with none of the Chart series. Style defines the type of series data to be displayed in the Mark Tips while Mouse Action sets whether the Mark Tips appear on a Mouse click or move. Delay desfines the lapse of time in milliseconds before the Mark Tips appear.

Run-time

Adding a Mark Tips Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcMarksTip
    With .Tools.Items(0)
        .Active = True
        With .asMarksTip
          .Delay = 1000
          .MouseAction = mtmMove
          .Series = 0
          .Style = smsXY
        End with
    End With
End With

Nearest Point Tool

The Nearest Point Tool moves a marker to the point nearest to the cursor. The tool may be associated with a Series or applied globally to the Chart.

Design-time

The Nearest Point Tool needs to be associated with a specific Chart Series. Its appearance can be configured using Pen to define the colour, style, width and visibility of the lines used to draw the Tool and Brush to define the colour and pattern or image used to fill the Tool's area. Draw Line enables/disables the drawing of the connecting line between the cursor position and the Nearest Point Tool shape, Size defines the size of this shape while Style defines the type of shape used.

Run-time

Adding a Nearest Point Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcNearest
    With .Tools.Items(0)
        .Active = True
        With .asNearest
          .DrawLine = True
          .Pen.Color = vbBlue
          .Series = 1
          .Size = 20
          .Style = hsDiamond
        End with
    End With
End With

Page Number Tool

The Page Number Tool displays a fully configurable text box containing a chosen page numbering system.

Design-time

The Text of the Page Number Tool and the box it sits in can both be fully configured. The Options tab allows you to enter the text you wish and to specify its alignment and the cursor type that appear when the mouse is over the Tool. The Position tab specifies the default or custom position of the Page Number Tool. The Callout tab defines the Page Number Tool's Callout object which is used to draw a line from the annotation to any position in the chart. The Format tab configures the text box, allowing you to change its colour, frame, pattern, bevel, size, roundness and transparency. The Text tab enables the setting of the text font, colour, outline and spacing and also the colour and size of the text shadow. The Gradient tab configures the properties of the text-box gradient while the Shadow tab configures the properties of the text-box shadow.

Run-time

Adding a Page Number Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcPageNumber
    With .Tools.Items(0)
        .Active = True
        .asPageNum.Position = ppRightTop
        .asPageNum.Shape.Gradient.Visible = True
    End With
End With

Pie Slices Tool

The Pie Slices Tool highlights the pie slice under the mouse either by drawing a border around it or by exploding it away from the rest of the Pie Series.

Design-time

The Pie Slices Tool has to be associated with a specific Pie Series before it will appear. Style specifies whether the tool will focus on the pie slice the mouse is over or whether it will explode it away from the rest. Border specifies the pen characteristics of the border which is drawn around a focussed pie slice.

Run-time

Adding a Pie Slices Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Aspect.View3D = False
    .AddSeries scPie
    .Series(0).asPie.Circled = False
    .Series(0).FillSampleValues 6

    .Tools.Add tcPie
    With .Tools.Items(0).asPie
        .Series = TChart1.Series(0)
        .Style = ptFocus
    End With
End With

Rotate Tool

The Rotate tool changes the elevation and rotation of charts when dragging the mouse over a chart.

Design-time

Rotate Tool designtime configurable properties include Inverted inverts the effect of mouse movement while rotating the chart, Style specifies whether the Chart is rotated, elevated or both, Button specifies which mouse button is used to rotate the chart while Outline configures the chart outline which can be drawn while the specified mouse button is being moved.

Run-time

Adding a Rotate Tool at runtime is a straightforward operation, as can be seen in the example below:

Example

With TChart1
    .Tools.Add tcRotate
    With .Tools.Items(0)
        .Active = True
        .asRotate.Button = mbRight
    End With
End With

Series Animation Tool

The Series Animation Tool performs a growing animation of Series Points.

Design-time

The Series Animation Tool has to be associated with a particular Series. Steps defines the number of animation steps taken by the Series Animation Tool, Start at Min value will start the animation from the minium Series YValue while Start Value specifies the start value when Start at Min value is set to false. Draw every will draw the series in groups of n points.

Run-time

Please find following a working example of the Series Animation Tool:

Example

Private Sub Command1_Click()
On Error Resume Next
HScroll1.Enabled = False
Command1.Enabled = False
TChart1.Tools.Items(0).asSeriesAnimation.Execute
HScroll1.Enabled = True
Command1.Enabled = True
End Sub

Private Sub Command2_Click()
TChart1.Tools.Items(0).ShowEditor
HScroll1.Value = TChart1.Tools.Items(0).asSeriesAnimation.Steps
End Sub

Private Sub Check1_Click()
  If Check1.Value = 1 Then
     TChart1.Tools.Items(0).asSeriesAnimation.DrawEvery = 1
  Else
     TChart1.Tools.Items(0).asSeriesAnimation.DrawEvery = 0
  End If
End Sub

Private Sub Form_Load()
TChart1.AddSeries scBar
TChart1.Series(0).ColorEachPoint = True
TChart1.Tools.Add tcSeriesAnimation
HScroll1.Min = 1
HScroll1.Max = 255
HScroll1.Value = 100

TChart1.Series(0).FillSampleValues 6
TChart1.Legend.Visible = False
TChart1.Series(0).ValueFormat = "000"
TChart1.Tools.Items(0).asSeriesAnimation.Series = TChart1.Series(0)
TChart1.Tools.Items(0).asSeriesAnimation.StartAtMin = False
End Sub

Private Sub HScroll1_Change()
TChart1.Tools.Items(0).asSeriesAnimation.Steps = HScroll1.Value
Label2.Caption = HScroll1.Value
End Sub

Private Sub HScroll1_Scroll()
Label2.Caption = HScroll1.Value
End Sub

Private Sub TChart1_OnSeriesAnimationToolStep(ByVal Tool As Long, ByVal Step As Long)
If Tool = 0 Then
    With TChart1
        .Series(0).PointColor(0) = RGB(255 - Step, Step, Step)
        .Series(0).PointColor(1) = RGB(Step, 255 - Step, Step)
        .Series(0).PointColor(2) = RGB(Step, Step, 255 - Step)
        .Series(0).PointColor(3) = RGB(255 - Step, 255 - Step, Step)
        .Series(0).PointColor(4) = RGB(Step, 255 - Step, 255 - Step)
        .Series(0).PointColor(5) = RGB(255 - Step, Step, 255 - Step)
    End With
End If
End Sub


// To test this file rename it with a .asp extension and
// place it in an executable rights directory in IIS server
// remove these three lines before running this example

<!--METADATA NAME="TeeChart Pro v2017 ActiveX Control" TYPE="TypeLib" UUID="{DE7847A7-A266-4AA9-AA68-16676652C9DB}"-->

<%
   'Send output to browser (and call RunChart method to build contents)
   Response.BinaryWrite(RunChart)
   Function RunChart()
    Dim img
    Dim Chart
        Set Chart = CreateObject("TeeChart.TChart")
        Chart.AddSeries(scBar)
    Chart.Series(0).Add 100, "Apples", RGB(255,0,0)
    Chart.Series(0).Add 300, "Pears", RGB(255,255,255)
    Chart.Series(0).Add 200, "Bananas", RGB(255,255,0)
    Chart.Export.asJPEG.CompressionQuality = 95
    Chart.Export.asJPEG.GrayScale = False
    Chart.Export.asJPEG.Height = 300
    Chart.Export.asJPEG.Width = 500
        img=Chart.Export.asJPEG.SaveToStream
        RunChart=img
        Set Chart=nothing
   End Function
%>


// To test this file rename it with a .asp extension, // place it in an executable rights directory in IIS server // and rename the paths below to reflect your server directories. // remove these four lines before running this example <% ' Server side execution dim outputfile ' the following line may be replaced with your dynamic ' name creation code: outputfile = "http://localhost/filename.tee" ' The following line requires that you have the teechart.ocx ' file registered on the server ' The Server Chart is called Chart1 Set Chart1 = CreateObject("TeeChart.TChart") Chart1.AddSeries(scLine) ' Use your methods eg. via DB to populate Chart or sample values ' for our example. Chart1.Series(0).FillSampleValues(10) ' Save the Chart as a .tee format file ' where the path locates to the same destination directory as ' the URL of the outputfile. Chart1.Export.SaveToFile "c:\inetpub\wwwroot\filename.tee" %> In the client section of the page we have added a TChart having the TeeChart OBJECT defined as name TChart1. Call the FillChart script with a button or Window_Onload event:

TChart1 on the browser page uses the TeeChart ActiveX control, teechart2017.ocx or teechart2017.cab loaded on the Client machine. This example uses the cabfile definition to download TeeChart to the client machine if it doesn't already exist.


TeeChart Native ODBC Page

// To test this file rename it with a .asp extension, // place it in an executable rights directory in IIS server // and rename the paths/DSNs below to reflect your server directories. // remove these four lines before running the example. TeeChart Native ODBC Page

This page connects a Server located Chart to an ODBC datasource and exports/imports the Chart to the browser located TChart where it can be zoomed/scrolled.

<%FillSave%>


TeeChart ADO ODBC Access

// To test this file rename it with a .asp extension, // place it in an executable rights directory in IIS server // and rename the paths/DSNs below to reflect your server directories. // remove these four lines before running the example. <% LANGUAGE="VBSCRIPT" %> TeeChart ADO ODBC Access

<% Dim Chart Set Conn = Server.CreateObject("ADODB.Connection") Set RS = Server.CreateObject("ADODB.RecordSet") Conn.Open "TeeChart Pro System db" RS.Open "select * from [employee]", Conn, 1,1 Set Chart = Server.CreateObject("TeeChart.TChart") Chart.AddSeries(0) Chart.AddSeries(0) Chart.Series(0).Color=&H00FF0000 Chart.Series(0).Title="My data Series" Chart.Series(0).DataSource = RS Chart.Series(0).LabelsSource = "LastName" Chart.Series(0).YValues.ValueSource = "Salary" Chart.Series(0).CheckDataSource Conn.Close Chart.Series(1).Title="Average" Chart.Series(1).SetFunction(5) Chart.Series(1).Color=&H0040FF00 Chart.Series(1).DataSource = "Series0" Chart.Series(1).FunctionType.Period = 0 Chart.Left=5 Chart.Top=5 Chart.Export.SaveToFile("c:\inetpub\wwwroot\testscripts\MyChart.tee") Set Chart = Nothing %>


Tutorial Contents

1. Getting Started
Introduction to design aspects of TeeChart Pro and a starter guide to building Charts.

2. Chart Display parameters
Chart display properties and methods using the Chart Editor and coded examples.

3. Chart Paging
How to configure multiple page charts.

4. Axis design
Advanced Axis design techniques.

5. Legend design
Advanced Legend design techniques.

6. Working with Series
Introduction to Series architecture and programming.

7. Working with Functions
TeeChart Pro Functions overview

8. ADO data access
How to use TeeChart Pro with ADO data sources

9. Internet applications
Guide to creating Internet/Intranet Charting applications

10. Walk-through VBScript examples
Some live Charts to show use of VBScript

11. Zoom and Scroll
How to zoom in and scroll your Charts

12. Exporting and Importing Charts
Exporting Charts to graphics format files and working with TeeChart's tee format templates.

13. Custom drawing on the Chart Panel
The Chart Canvas.

14. Printing Charts
Print methods and properties.

15. MS VC++ Applications
Building VC++ apps with TeeChart.

16. Chart 3D and OpenGL
3D features discussed.

17. TeeChart's additional palette components
3D features discussed.

18. TeeChart runtime installation requirements
Which files to install/register for runtime.

19. The TeeChart Tool collection
NEW v5 Tools explained

© 1998-2017 Steema Software SL. All rights reserved.