Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
TitleGraph an equation Y = F(X) using MSChart
KeywordsMSChart, graph, equation, chart
CategoriesGraphics, Controls
 
When you click the Graph command, the CmdGraph_Click event handler reads parameters for the equation

    Y = N * X ^ 2 - M * X + b

It then loops over X values calculating Y values and adding them to the values array. When it is finished, the control sets the MSChart control's ChartData property to the array of values. It finishes by setting some chart properties.

 
Private Sub CmdGraph_Click()
Dim M As Single
Dim N As Single
Dim b As Single
Dim xmin As Single
Dim xmax As Single
Dim xstep As Single
Dim X As Single
Dim values() As Single
Dim i As Integer
Dim num_x As Integer

    M = CSng(MText.Text)
    N = CSng(NText.Text)
    b = CSng(bText.Text)
    xmin = CSng(XminText.Text)
    xmax = CSng(XmaxText.Text)
    xstep = CSng(StepText.Text)
    num_x = (xmax - xmin) / xstep
    ReDim values(1 To num_x, 1 To 2)
        
    ' Compute the data values.
    X = xmin
    For i = 1 To num_x
        values(i, 1) = M * X + b
        values(i, 2) = N * X ^ 2 - M * X + b
        X = X + xstep
    Next i

    ' Send the data to the chart.
    Chart1.RowCount = 2
    Chart1.ColumnCount = num_x
    Chart1.ChartData = values
    Chart1.chartType = VtChChartType2dLine

    ' Create the legend.
    With Chart1.Legend
        .Location.Visible = True
        .Location.LocationType = VtChLocationTypeRight
        .TextLayout.HorzAlignment = _
            VtHorizontalAlignmentRight
    End With
    
    ' Set the legend text for the series.
    Chart1.Plot.SeriesCollection(1).LegendText = "Straight " & _
        "Line"
    Chart1.Plot.SeriesCollection(2).LegendText = "Quadratic"
End Sub
 
My book Custom Controls Library implements a control that does simple graphics without the MSChart control.

Tip: Setting properties in code like this rather than at design time can be very useful for controls such as MSChart that get upgraded frequently. If you install a newer version of the control and remove the old version, then when you open an application the old control is replaced by a PictureBox and all of its properties are lost (although you can still read them in the .frm file with a text editor). If you set the properties in the code, you only need to replace the control and the code can set the properties for the new control.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated