Adding Events To A Chart In Microsoft Visual Studio 2010
In this tutorial we will use the PostPaint event to customize our chart, adding a dynamic shape to mark the highest sales last year. To complete this tutorial you must have completed Data Binding A Chart To A Database.Download the source file if you do not have the previous version.
1. First off, we need to access our code-behind file of the page our chart is on. Add the following using statement to the top of the page.
2. In the Page_Load event, add the following line of code to create our PostPaint event at runtime.
this.Chart1.PostPaint += new EventHandler
3. Navigate to the Properties window of our chart. In that window you will see an Events Icon (Lightning Bolt Icon). Once in that window, double click the PostPaint property and it will create the Chart1_PostPaint event handler and take us back to the code behind.
4. Place the following code Inside of the Chart1_PostPaint Event.
protected void Chart1_PostPaint(object sender, ChartPaintEventArgs e)
// Make sure all series have been drawn before proceeding
if (e.ChartElement is Series && ((Series)e.ChartElement).Name == "Series1")
Series s = e.Chart.Series;
ChartGraphics cg = e.ChartGraphics;
double max = s.Points.FindMaxByValue().YValues;
// Highlight the maximum sales this year
for (int i = 0; i < s.Points.Count; i++)
if (s.Points[i].YValues == 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+1);
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,
5. What we have done is select our series. We run through that series with a for loop and pull each data point out. We then have access to the values in that series and set our shape that we created with (cg.Graphics.DrawEllipse) to the max Y and the correct X value.
6. Run the application. Now whenever you load up the page the sales person with the most sales will have a marker at the top of his or her sales.
Notifications such as these are powerful ways to keep your users constantly updated. For instance this chart could be easily modified to watch daily values and change throughout the day to reflect how something or someone is doing. Congratulations you are now building fully functional dynamic charts!