Friday, April 17, 2009

Forcing label values to be displayed to the right of a bar (ASP.NET 3.5 chart control)

As I've previously written, the new ASP.NET 3.5 chart control is great. However, a minor thing that doesn't work well is displaying value labels for bar charts. It displays the value to the right of the bar except for the longest bar when it determines that it wouldn't fit within the scale. So, if you have a bar with a value of 98, and you have your axis interval set to 25, it will display "98" in the bar. This doesn't necessarily look good, depending on what color the bar is, and it is also inconsistent with the other bars.

Here's my solution (C#):

Chart1.DataBound += delegate(System.Object o, System.EventArgs ea) {
double longestBarLength = Chart1.Series[0].Points.FindMaxByValue().YValues[0],
padding = 10d,
roundedUpBarLengh = Math.Ceiling((longestBarLength + padding) / 25) * 25;

Chart1.ChartAreas[0].AxisY.Maximum = roundedUpBarLengh;

I'm determining the longest bar length w/out looping thanks to a nice built-in function "FindMaxByValue()" which gets me access to the DataPoint object with the largest value, and I'm just grabbing the Y Value from it (in my case, there's only one Y value).

Then I specify a set padding to make room for the value label to be displayed on the right side of the bar (10 seems to work well for numbers in the 100's at least). Lastly I'm pushing the value whatever the longest bar length is to the nearest 25 and setting the axis max value to that number.

This all needs to be done after the data is already there, obviously, so this is all wrapped in the databound event handler.

I'll add pics later.

No comments: