MSDN Library

Tutorial: Customizing a Chart with Events

This tutorial demonstrates how to use events to customize your chart. You will add a custom marker at the maximum data point to highlight the sales person that has the highest sales this year.

To complete this tutorial, you must have completed the tutorial in Tutorial: Data Binding a Chart to a Database

To begin, open the code-behind file in your ASP.NET application, or switch to code view in your Windows Form application.

At the top of the code file, add the Chart namespace as shown below.

// For Windows Forms
using System.Windows.Forms.DataVisualization.Charting;
// For ASP.NET
using System.Web.UI.DataVisualization.Charting;

Add an event handler for the Chart.PostPaint event.

In Windows Forms, you do this in the form's constructor, just after the InitializeComponent method. In ASP.NET, you do this in the Page_Load event handler method that is automatically created.

this.Chart1.PostPaint += new EventHandler<ChartPaintEventArgs>(Chart1_PostPaint);

Then, add the method definition for the event handler you just registered. To do this, add the following code into the class definition.

void Chart1_PostPaint(object sender, ChartPaintEventArgs e)

You will now add custom code that highlights the salesperson that has the highest sales this year. To do this, add the code below to the Chart1_PostPaint event handler you just created, save the file, and run your application.

// Make sure all series have been drawn before proceeding
if (e.ChartElement is Series && ((Series)e.ChartElement).Name == "Series2" )
    Series s = e.Chart.Series[0];
    ChartGraphics cg = e.ChartGraphics;
    double max = s.Points.FindMaxByValue().YValues[0];

   // Highlight the maximum sales this year
   for(int i = 0; i < s.Points.Count; i++)
      if(s.Points[i].YValues[0] == max)
         // Get relative coordinates of the data point
         System.Drawing.PointF pos = System.Drawing.PointF.Empty;
         pos.X = (float)cg.GetPositionFromAxis("ChartArea1", AxisName.X, i);
         pos.Y = (float)cg.GetPositionFromAxis("ChartArea1", AxisName.Y, max);

         // Convert relative coordinates to absolute coordinates.
         pos = cg.GetAbsolutePoint(pos);

         // Draw concentric circles at the data point
         for (int radius = 10; radius < 40; radius += 10)
               pos.X - radius / 2, 
               pos.Y - radius / 2, 
               radius, radius);
© 2015 Microsoft