(Print this page)

The Chart control in Visual Studio 2010 (and 2008 to some extents)
Published date: Tuesday, January 4, 2011
On: Moer and Éric Moreau's web site

For a long time, when you wanted to add nice charting to your application, you had to buy an external library. With the latest release of Visual Studio, namely 2010, this is not true anymore as Microsoft packaged a great charting control into Visual Studio. If you are still using Visual Studio 2008, check the bottom of the article.

The control is provided for both Windows Forms and ASP.Net.

If I am not mistaken, this control was originally created by Dundas for which Microsoft made a special arrangement because they needed one for SSRS (SQL Server Reporting Services).

The downloadable code

This month downloadable demo will only work with Visual Studio 2010 because the chart control is only provided with this version.

I have also created the demo application in both VB and C#.

Figure 1: The demo application

Find the control

The first thing you need to know is where to find this control in your toolbox to be able to drop it on one of your forms.

As shown in figure 1, you will find this control under the Data tab.

Figure 2: Finding the chart control in the toolbox

Series Collection

There is one important thing you need to understand when you work with the Chart control. You need to understand the Series collection. This collection contains all the sets of data for the chart. If you were to make a simple line graph (like we will do soon), your series would be all the points for that line. But a series is much more than just the data points. It is also the caption on the legend, the type (line, bar, point …), color, thickness, marker style, tooltip …

And because series is a collection, which means that a single chart can contain multiple series (for example estimated sales and real sales).

I am sure that you have now guessed that we will work a lot with series in this article!

Sample 1

In the first sample, I will use about the less code possible to demonstrate the basic feature and the default values.

So here is my code:

Dim objRandom As New Random

With Me.Chart1
    Me.ResetChart()

    'Create a new series for visitors
    With .Series.Add("Visitors")
        'Set random numbers
        For intDay As Integer = 1 To 31
            .Points.AddXY(intDay, objRandom.Next(5000))
        Next
    End With
End With

What I do here is that I reset the chart to its original value (by calling Me.ResetChart which is a method I wrote). Then I create a new series that I name Visitors. Finally, I add 31 random values (between 0 and 5000) to fake the number of visitors in the month of January.

Sample 2

The second example is very much like the first one except that I will use some of the features.

This is my new code:

Dim objRandom As New Random

With Me.Chart1
    Me.ResetChart

    'add a title
    With .Titles.Add("January visitors")
        .Font = New Font("Verdana", 16, FontStyle.Bold)
    End With

    'Create a new series for visitors
    With .Series.Add("Visitors")
        'Change the default color (blue) to red
        .Color = Color.Red
        'change the default type (column) to line
        .ChartType = DataVisualization.Charting.SeriesChartType.Line

        'Set random numbers
        For intDay As Integer = 1 To 31
            .Points.AddXY(String.Format("{0} ({1})", New Date(2011, 1, intDay).ToString("ddddd"), intDay), objRandom.Next(5000))
        Next
        .ToolTip = "#VALX"
    End With

    'to ensure we see all the values on the X axis
    .ChartAreas(0).AxisX.Interval = 1
    'set an angle to the label
    .ChartAreas(0).AxisX.LabelStyle.Angle = 45
 End With

As you can see here, I have added a title to the chart so it is now clearer on what it is (using the Titles collection). I have also changed the default blue color to red. I changed the default column type to now have the data shown using a line. Instead of having the X axis showing the day number, it is now showing the name of the day followed by its value. I have also added a statement to let the chart show the value of X axis as a tooltip when hovering a value of the chart (this one is not trivial – more expressions at http://blogs.msdn.com/b/alexgor/archive/2008/11/11/microsoft-chart-control-how-to-using-keywords.aspx). Finally, because we want to see all the days on the X axis, I had to specify the interval for this axis to 1 (otherwise it would skip many days).

Sample 3

In the third sample, I will show you how to build a pie chart.

This is my code.

Dim objRandom As New Random

With Me.Chart1
    Me.ResetChart()

    'Create a new series
    With .Series.Add("Canadian provinces")
        'change the default type (column) to Pie
        .ChartType = DataVisualization.Charting.SeriesChartType.Pie

        'Set random numbers
        For Each strX As String In New String() {"Edmonton (AB)",
                                                 "Victoria (BC)",
                                                 "Charlottetown (PEI)",
                                                 "Winnipeg (MB)",
                                                 "Fredericton (NB)",
                                                 "Halifax (NS)",
                                                 "Toronto (ON)",
                                                 "Québec (QC)",
                                                 "Regina (SK)",
                                                 "St. John's (NF)"}
            .Points.AddXY(strX, objRandom.Next(1000))
        Next

        .IsVisibleInLegend = False
        .Label = "#VALX\n#PERCENT"
    End With

    'force labels to appear outside the pie
    .Series("Canadian provinces")("PieLabelStyle") = "Outside"

    'set the pie to be in 3D
    .ChartAreas(0).Area3DStyle.Enable3D = True
End With

This time the series is listing the capitals of the 10 Canadian provinces along with a random value (between 0 and 1000). I have set the IsVisibleInLegend to False because in this case, the same value would be shown both on the pie and in the legend. I also specify the label of each part to be the name of the capital to which the percentage is appended (using the Label property). Because the labels are a bit long, I force the labels to appear outside the pie itself. Finally, I set the pie to appear in 3D.

Sample 4

This last sample will show you how to use multiple series on a single chart.

So this is my code:

Dim objRandom As New Random

With Me.Chart1
    Me.ResetChart()

    'Create new series for 2 teams
    For intTeam As Integer = 1 To 2
        With .Series.Add("Team " + intTeam.ToString)
            'Set random scores
            For intDay As Integer = 1 To 10
                .Points.AddXY(intDay, objRandom.Next(7))
            Next
        End With
    Next

    'a little gymnastic to print the score for each game
    For intDay As Integer = 1 To 10
        Dim cl As New DataVisualization.Charting.CustomLabel
        cl.FromPosition = (intDay - 1) + 0.5
        cl.ToPosition = intDay + 0.5
        cl.Text = "Game " + intDay.ToString +
                  "\n" +
                  Chart1.Series(0).Points(intDay - 1).YValues(0).ToString +
                  "-" +
                  Chart1.Series(1).Points(intDay - 1).YValues(0).ToString
        .ChartAreas(0).AxisX.CustomLabels.Add(cl)
    Next

    'set some styling
    .Series(0)("DrawingStyle") = "Wedge"
    .Series(1)("DrawingStyle") = "Wedge"
End With

Because no chart type has been set, this chart will show columns. I specifically create 2 series (Team 1 and Team 2). Each series contains 10 points set randomly between 0 and 7 (for 10 games in my scenario). After the series have been created, I do a special loop to set the label of each game to the score of the game by creating a custom label object and adding it to the X axis.

What about Visual Studio 2008?

All is not lost! You can download and use for free the Microsoft Chart Controls for the .Net Framework 3.5 from http://www.microsoft.com/downloads/en/details.aspx?FamilyId=130F7986-BF49-4FE5-9CA8-910AE6EA442C&displaylang=en. Be aware that you will need the SP1 to be able to use this package.

This package is very similar to the one I have demonstrated here.

More samples

Microsoft provides many samples dedicated to the chart control on the MSDN Code Gallery for both Windows Forms and ASP.Net and for both Visual Studio 2008 and 2010. You can get them from http://code.msdn.microsoft.com/mschart.

Figure 3: Interactive samples from MSDN

I really encourage you to download these samples as it really shows the benefits of using this control. It contains about 200 interactive samples letting you discover what the features are and even show you some code.

Conclusion

We have been missing this control for a long time. It is now really easy to include really good looking chart controls in your application.


(Print this page)