SharePoint 2010: Adding Charts to Standard Webparts and Visual Webparts

SharePoint 2010: Adding Charts to Standard Webparts and Visual Webparts

Adding charts to webparts is actually pretty easy; here's how.

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.

Add the Http Handler for the chart images:

<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>

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>

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)!


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 add the chart control directly onto 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>

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;
        }
    }
}

Questions were asked about this in the following posts:
http://social.technet.microsoft.com/Forums/en-US/sharepointdevelopmentprevious/thread/c7ef203d-8738-4d33-a087-1a963c1b3ee6
http://social.technet.microsoft.com/Forums/en-US/sharepointdevelopmentprevious/thread/08aee6e1-57f3-4660-b76a-f7044439ef10

I blogged about this a while ago, getting data from SQL instead of a SharePoint list, which you can view here: http://matthewyarlett.blogspot.co.uk/2012/02/adding-graphs-to-sharepoint-webparts.html


Leave a Comment
  • Please add 3 and 1 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Ed Price - MSFT edited Revision 13. Comment: Making the technology more obvious in the title.

  • Ed Price - MSFT edited Revision 11. Comment: HTML bug

  • Ed Price - MSFT edited Revision 9. Comment: Going to try just removing the period from the title

  • Ed Price - MSFT edited Revision 8. Comment: Reverting. I ruined the great code coloring. =^(

  • Ed Price - MSFT edited Revision 6. Comment: Removed period from title per guidelines. Great article!

  • Matthew Yarlett edited Revision 3. Comment: Fixed code formatting  

  • Matthew Yarlett edited Revision 2. Comment: Minor changes to wording

  • Matthew Yarlett edited Revision 1. Comment: Added an example for adding a chart to a visual webpart

  • Matthew Yarlett edited Original. Comment: Minor change to gramma

Page 1 of 1 (9 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Matthew Yarlett edited Original. Comment: Minor change to gramma

  • Matthew Yarlett edited Revision 1. Comment: Added an example for adding a chart to a visual webpart

  • Matthew Yarlett edited Revision 2. Comment: Minor changes to wording