Data Source
First, let’s generate some data to display via the chart. We will create it at design time to allow us to get on with the core Graphics Class parts of the project. If you prefer to have the data input by the user at run time then you can adapt the techniques covered in Part 3.
Create Data
Shown below is what has become our standard code to create initial variables and to generate and store some data. I won’t trundle through the details as they are fully covered in earlier articles:
Option Strict On
Imports System.Drawing.Drawing2D
Imports System.Collections
Structure GraphData
Dim Country As String
Dim Sales As Integer
Dim BarColor As Color
Sub New(ByVal country As String, ByVal sales As Short, ByVal barcol As Color)
Me.Country = country
Me.Sales = sales
Me.BarColor = barcol
End Sub
End Structure
' Create Variables
‘ # of pixels vertical Axis is inset from PictureBox Left
Dim LeftMargin As Integer = 35
' # of Pixels left unused at right side of PictureBox
Dim RightMargin As Integer = 15
' The number of pixels above bottom of baseline
Dim BaseMargin As Integer = 35
' Margin at Top
Dim TopMargin As Integer = 10
' Set size of gap between each bar
Dim BarGap As Integer = 12
Dim SalesData As New ArrayList
Dim HighSale As Double ' Maximum sales figure
Dim VertScale As Double ' Scaling used for bar heights
' Minor changes for this version:
' Declare a variable to hold a Graphics object
Dim g As Graphics
' Variable for Bitmap to be displayed in (PictureBox) control
Dim bmap As Bitmap
' Length of vertical axis
Dim VertLineLength As Integer
Dim BarWidth As Integer ' width of bars
Dim BaseLineLength As Integer ' X Axis length
Private Sub GetData()
SalesData.Clear() ' Avoid data duplication
' Generate some data and store it in the arraylist
SalesData.Add(New GraphData("Belgium", 934, Color.Blue))
SalesData.Add(New GraphData("Greece", 385, Color.DarkOrange))
SalesData.Add(New GraphData("Portugal", 1029, Color.Green))
SalesData.Add(New GraphData("Spain", 729, Color.IndianRed))
SalesData.Add(New GraphData("Turkey", 1472, Color.Tomato))
SalesData.Add(New GraphData("UK", 1142, Color.Aquamarine))
End Sub
Controls
Add a PictureBox named PBBarChart and a Button named btnDraw to the Form.
Place the button somewhere down in the bottom corner of the Form.
Stretch the PictureBox so that it is close to the top, right and left edges of the form. Set its Anchor property so that it is anchored to all four sides. Doing this will allow the user to click the button for a resized version of the chart to be displayed whenever the form size is altered . (As we will see in later articles, there are more dynamic ways of achieving this, but we’ll stick with this method for now.)