C# Charts

One of the uses we can make of a Windows form is to display data in a chart. There are numerous kinds of charts: vertical bars, horizontal bars, pie charts, doughnut charts, etc.

Suppose we want to create a chart.

Start a Windows Form application.

Call up the Toolbox menu, scroll down if necessary and select Chart. Drag it to the vacant form. This is a default chart with some sample data.

As with any control, you can right-click on the chart and see the Properties menu. As usual, there are many choices.

Locate "Series" which is listed as a Collection. Click on it and you will now have three dots over at its right (...). Click on them and you will be in the Series Collection Editor. This allows you to indicate which kind of chart you want and to input a sequence of values to be charted. One of the choices is "Add", which adds a new series. You may have several series displayed in one chart; they will be in different colors.

If you select "Chart", one of the choices is "Chart Type", listing many kinds of charts. Let's try bar charts for now.

Below that is "Data", and one of the choices is "Points". If you click on it, you will again see three dots at the right (...), and if you click on them, you will be in the DataPoint Collection Editor. This affects whichever series is highlighted in the Series Collection Editor. You can add or remove points. If you choose "Add", you can then find the spot marked "Y Value" and type in the number you want. When you click OK, the DataPoint Collection Editor closes and you are back in the Series Collection Editor. Click OK again.

The chart displayed in your form is updated as you do all this. You may want to move the windows for the editors so you can see what is happening.

The code generated when you add a Y Value looks like this:

     System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint1 = 
          new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 1.2D);

followed by

     series1.Points.Add(dataPoint1);

If you add points by hand in the Designer, the code will be generated by the Designer. In theory, you should be able to put the code elsewhere: you could read a file of numbers, create a DataPoint for each (in an array of DataPoint), and add each of them to a series.

We can have multiple charts in one form.

We can, of course, have labels for the charts.