SharePoint 2010: Adding Charts to Webparts

SharePoint 2010: Adding Charts to Webparts


 

Introduction


Adding charts to your webparts to display information visually can making data much easier to understand, and it's is actually pretty easy. This article covers an example of adding a chart to standard webpart and a visual webpart. 

Add the HTTP Handler for the Chart Images


You need to add the ChartImageHandler to the web.config of the Web Application that will host the webpart before you start using code that generates chart images, so let's do this first.

Add a new HTTP Handler


<handlers>
    <add name="ChartImageHandler" verb="*" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</handlers>

Configure the ChartImageHandler


Add a new key to the <appSettings> section to configure the location (among other things) the image files are written to (see: Image File Management (Chart Controls) for more information):

<appSettings>   
    <add key="ChartImageHandler" value="storage=file;timeout=20;dir=c:\Temp\;" />
</appSettings>


Adding a Chart to a Standard Webpart


1. Create a new Empty SharePoint project in Visual Studio
2. Add a reference to Microsoft.Web.UI.DataVisualization (it's here by default: C:\Program Files (x86)\Microsoft Chart Controls\Assemblies\)
3. Add a new standard webpart to your project
4. In the webparts class file, add a using statement for the chart controls

using System.Web.UI.DataVisualization.Charting;

5. Add a chart control

private Chart chart;

6. Initialize the chart control in the OnInit event

protected override  void OnInit(EventArgs e)
{
    base.OnInit(e);
    chart = new  Chart();
    chart.Visible = false;
    chart.RenderType = RenderType.ImageTag;
    chart.ImageType = ChartImageType.Png;
}

7. Add the chart to the page in the CreateChildControls method

protected override  void CreateChildControls()
{
    EnsureChildControls();
    Controls.Add(chart);
}

8. Populate the control with some data in the OnPreRender event. Here I'm getting a bunch of values from a list that has the number of crazy things I've done in recent years.

protected override  void OnPreRender(EventArgs e)
{
    base.OnPreRender(e);
    PopulateChart(SPContext.Current.Web.Lists["crazythingslist"]);
}

The PopulateChart method gets the Series data (using an SPQuery to query the list passed into the method), creates a new ChartArea, and adds it all to the chart. It also sets some of the charts properties, like height and width.

private void  PopulateChart(SPList dataList)
{
    try
    {
        chart.Width = 315;
        chart.Height = 150;
        chart.AntiAliasing = AntiAliasingStyles.All;
        chart.TextAntiAliasingQuality = TextAntiAliasingQuality.High;
        Series s = GetCrazyThingsData(dataList);
        ChartArea ca = ChartArea();
        chart.ChartAreas.Add(ca);
        chart.Series.Add(s);
        chart.Visible = true;
    }
    catch
    {
        chart.Visible = false;
    }
}
 
private static  ChartArea ChartArea()
{
    ChartArea chartArea = new  ChartArea();
    chartArea.BackColor = Color.Gray;
    chartArea.BackSecondaryColor = Color.DarkGray;
    chartArea.BackGradientStyle = GradientStyle.TopBottom;
    chartArea.AxisY.Title = "Craziness Count";
    chartArea.AxisX.Title = "Crazy things, Recent Years";
    chartArea.AxisX.Interval = 1;
    return chartArea;
}
 
private Series GetCrazyThingsData(SPList dataList)
{
    var series = new  Series();
    series.Color = Color.ForestGreen;
    series.BackSecondaryColor = Color.GreenYellow;
    series.BorderColor = Color.Firebrick;
    series.BackGradientStyle = GradientStyle.TopBottom;
 
    var query = new  SPQuery();
    query.Query = "<OrderBy><FieldRef Name=\"Year\"/></OrderBy>";
    query.RowLimit = 50;
    var items = dataList.GetItems(query);
    foreach (SPItem i in items)
    {
        var yearCountObj = Int32.Parse(i["NumberOfCrazyThingIveDone"].ToString());
        var yearObj = Int32.Parse(i["Year"].ToString());
        var p = new  DataPoint
            {
                XValue = yearObj,
                YValues = new[] {Convert.ToDouble(yearCountObj)}
            };
        series.Points.Add(p);
    }
    return series;
}

9. Now we're nearly ready to deploy... but first we need to add the httphandler to the web.config file for the web application you are going to be deploying the webpart to. To do this, you'll need to add an entry into the <handlers> section and the <appSettings> sections of the web.config file.

10. Lastly, deploy your solution to SharePoint and add your webpart to the page. Hopefully it will look something similar to the one below (or the same if you stole my data)!



Adding a Chart to a Visual Webpart


The only real difference when adding a chart to a Visual Webpart, is that you need to register the charting controls on the ascx page and then add the chart control directly in the pages markup (you don't need to initialize the control on the OnInit event).

Page Markup



<!-- Other Assemblies, Registers, etc -->
<%@ Import Namespace="Microsoft.SharePoint" %>
<div>
    <charts:Chart ID="chart" runat="server" RenderType="ImageTag" ImageType="Png"></charts:Chart>   
</div>

Visual Webpart's Code File


And the code in your visual webparts file should look like this:

using System;
using System.ComponentModel;
using System.Drawing;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
 
namespace ChartWebPart.CoolChartVisualWebpart
{
    [ToolboxItemAttribute(false)]
    public partial  class CoolChartVisualWebpart : WebPart
    {       
        public CoolChartVisualWebpart()
        {
        }
 
        protected override  void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }
 
        protected void  Page_Load(object sender, EventArgs e)
        {
        }
 
        protected override  void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            PopulateChart(SPContext.Current.Web.Lists["mylistwithdatainit"]);
        }
 
        private void  PopulateChart(SPList dataList)
        {
            try
            {
                chart.Width = 315;
                chart.Height = 150;
                chart.AntiAliasing = AntiAliasingStyles.All;
                chart.TextAntiAliasingQuality = TextAntiAliasingQuality.High;
                Series s = GetCrazyThingsData(dataList);
                ChartArea ca = ChartArea();
                chart.ChartAreas.Add(ca);
                chart.Series.Add(s);
                chart.Visible = true;
            }
            catch
            {
                chart.Visible = false;
            }
        }
 
        private static  ChartArea ChartArea()
        {
            ChartArea chartArea = new  ChartArea();
            chartArea.BackColor = Color.Gray;
            chartArea.BackSecondaryColor = Color.DarkGray;
            chartArea.BackGradientStyle = GradientStyle.TopBottom;
            chartArea.AxisY.Title = "Craziness Count";
            chartArea.AxisX.Title = "Crazy things, Recent Years";
            chartArea.AxisX.Interval = 1;
            return chartArea;
        }
 
        private Series GetCrazyThingsData(SPList dataList)
        {
            var series = new  Series();
            series.Color = Color.ForestGreen;
            series.BackSecondaryColor = Color.GreenYellow;
            series.BorderColor = Color.Firebrick;
            series.BackGradientStyle = GradientStyle.TopBottom;
 
            var query = new  SPQuery();
            query.Query = "<OrderBy><FieldRef Name=\"Year\"/></OrderBy>";
            query.RowLimit = 50;
            var items = dataList.GetItems(query);
            foreach (SPItem i in items)
            {
                var yearCountObj = Int32.Parse(i["NumberOfCrazyThingIveDone"].ToString());
                var yearObj = Int32.Parse(i["Year"].ToString());
                var p = new  DataPoint
                {
                    XValue = yearObj,
                    YValues = new[] { Convert.ToDouble(yearCountObj) }
                };
                series.Points.Add(p);
            }
            return series;
        }
    }
}

See Also

An important place to find a huge amount of SharePoint related articles is the TechNet Wiki itself. The best entry point is SharePoint Resources on the TechNet Wiki

References



Sort by: Published Date | Most Recent | Most Useful
Comments
  • Matt, very nice article.  When I start to get my head around the coding, I'll give this a go.  Good luck for the Monthly Guru entry!