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
Adding the Chart Namespace
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.
Adding the PostPaint Event
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.
Then, add the method definition for the event handler you just registered. To do this, add the following code into the class definition.
Perform Custom Painting
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 TypeOf e.ChartElement Is Series AndAlso DirectCast(e.ChartElement, Series).Name = "Series2" Then Dim s As Series = e.Chart.Series(0) Dim cg As ChartGraphics = e.ChartGraphics Dim max As Double = s.Points.FindMaxByValue().YValues(0) ' Highlight the maximum sales this year For i As Integer = 0 To s.Points.Count - 1 If s.Points(i).YValues(0) = max Then ' Get relative coordinates of the data point Dim pos As System.Drawing.PointF = System.Drawing.PointF.Empty pos.X = CSng(cg.GetPositionFromAxis("ChartArea1", AxisName.X, i+1)) pos.Y = CSng(cg.GetPositionFromAxis("ChartArea1", AxisName.Y, max)) ' Convert relative coordinates to absolute coordinates. pos = cg.GetAbsolutePoint(pos) ' Draw concentric circles at the data point For radius As Integer = 10 To 39 Step 10 cg.Graphics.DrawEllipse(System.Drawing.Pens.Red, _ CSng(pos.X - radius / 2), _ CSng(pos.Y - radius / 2), radius, radius) Next End If Next End If