MSChart - Dynamic assign ChartArea, Series, Legends etc..

This tutorial will help you how to install the MS Chart extension and create a column graph with MS Chart in ASP.NET 3.5 (C#).
Note: MS Chart will work with ASP.NET 3.5 and above only.

Download and install: Microsoft Chart Controls for Microsoft .NET Framework 3.5
http://www.microsoft.com/downloads/details.aspx?FamilyID=130f7986-bf49-4fe5-9ca8-910ae6ea442c&displaylang=en

Chart Control to your toolbox: Right-click > Choose Items > Program Files > Microsoft Chart Controls > System.Web.DataVisualization.dll.
Adding Reference-: Program Files > Microsoft Chart Controls > System.Web.DataVisualization.dl
Also, we need Web.config entry reference-:

<system.web>
 <httpHandlers>
  <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
 </httpHandlers>
</system.web>

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

Now we can start, create a new website. Drag and Drop the MS Chart from the toolbox onto webpage.

<asp:Chart ID="Chart2" runat="server" Width="800px" Height="300px"></asp:Chart>

An example how to assign ChartArea name, create Series, Legends, ToolTip etc.. on codebehind.
Table and sql statement are used from my sample DB.

 String connString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString();
 String sSQL = "select distinct subject, marks FROM tblStudentMarks order by 2";
 DataTable result = new DataTable();
 using (SqlConnection conn = new SqlConnection(connString))
 {
  using (SqlCommand cmd = new SqlCommand())
  {
   conn.Open();
   cmd.CommandText = sSQL;
   cmd.Connection = conn;
   SqlDataReader dr;
   dr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
   result.Load(dr);
   dr = null;
  }
 }
 String sSeries = "";
 //Assaigning ChartArea Name
 Chart2.ChartAreas.Add("chtArea");
 //Binding to Legends
 Chart2.Legends.Add("chtArea");
 LegendItem legendItem = new LegendItem();
 for (int i = 0; i < result.Rows.Count; i++)
 {
  sSeries = result.Rows[i][0].ToString().ToUpper();
  if(Chart2.Series.FindByName(sSeries) == null)
  {
   //Creating Unique Series
   Chart2.Series.Add(sSeries);
   legendItem.Name = sSeries;
   //Below some properties... of Legends
   legendItem.BorderWidth = 4;
   legendItem.ShadowOffset = 1; 
   legendItem.Color = Color.FromName(Chart2.Series[sSeries].Color.Name.ToString());
   legendItem = new LegendItem();
  }
  Chart2.Series[sSeries].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Column;
  //Chart2.Series[sSeries].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Bar;

  //Binding UserCounts
  Chart2.Series[sSeries].Points.AddY(Convert.ToDouble(result.Rows[i][1].ToString()));

  //Series properties
  Chart2.Series[sSeries].IsVisibleInLegend = true;
  Chart2.Series[sSeries].IsValueShownAsLabel = true;
  Chart2.Series[sSeries].ToolTip = "Data Point Y Value: #VALY{G}";
 }
 result = null;

 //Axis properties
 Chart2.ChartAreas[0].AxisX.Title = "User Roles";
 Chart2.ChartAreas[0].AxisX.TitleFont = new System.Drawing.Font("Verdana", 10, System.Drawing.FontStyle.Bold);
 Chart2.ChartAreas[0].AxisY.Title = "User Count";
 Chart2.ChartAreas[0].AxisY.TitleFont = new System.Drawing.Font("Verdana", 10, System.Drawing.FontStyle.Bold);
 Chart2.ChartAreas[0].AxisY2.LineColor = Color.Black;
 Chart2.ChartAreas[0].BorderDashStyle = ChartDashStyle.Solid;
 Chart2.ChartAreas[0].BorderWidth = 1;
 Chart2.BorderSkin.SkinStyle = BorderSkinStyle.Emboss;
 Chart2.BorderlineColor = System.Drawing.Color.FromArgb(26, 59, 105);
 Chart2.BorderlineWidth = 2;
 Chart2.BackColor = Color.AliceBlue;

 //Legends properties
 for (int j = 0; j < Chart2.Legends.Count; j++)
 {
  Chart2.Legends[j].BorderColor = Color.Black;
  Chart2.Legends[j].BorderWidth = 1;
  Chart2.Legends[j].BorderDashStyle = ChartDashStyle.Solid;
  Chart2.Legends[j].ShadowOffset = 1;
  Chart2.Legends[j].LegendStyle = LegendStyle.Table;
  Chart2.Legends[j].TableStyle = LegendTableStyle.Auto;
  Chart2.Legends[j].Docking = Docking.Bottom;
  Chart2.Legends[j].Alignment = StringAlignment.Center;
  Chart2.Legends[j].Enabled = true;
  Chart2.Legends[j].Font = new System.Drawing.Font("Verdana", 8, System.Drawing.FontStyle.Bold);
  Chart2.Legends[j].AutoFitMinFontSize = 5;
 }
Published Tuesday, October 20, 2009 5:29 PM by Suthish Nair

Comments

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Monday, November 23, 2009 2:22 AM by MK

can we define x axis interval at our own

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Thursday, December 24, 2009 5:18 AM by Suthish Nair

Sorry for late relpy...

yes we can

Chart2.ChartAreas["chtArea"].AxisX.Interval = 1;

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Sunday, January 31, 2010 8:46 PM by ccko

Hello,

i want disable x and y axis' grid line and add only three y axis line.

Chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;

Chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;

i don't know how to add 3 y axis grid lines.

could you tell me how to do it?

thanks for you help

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Wednesday, February 17, 2010 12:48 AM by Raj

In this article is very useful.Thanks

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Friday, March 26, 2010 12:26 PM by venkysmv85

ERROR

A chart element with the name 'LightBlue' could not be found in the 'SeriesCollection'.

I AM TRYING THIS FOR LONG, HOPE U WILL HELP ME OUT

VENKYSMV85@GMAIL.COM

C# CODE

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.Web.UI.DataVisualization.Charting;

public partial class Default3 : System.Web.UI.Page

{

   protected void Page_Load(object sender, EventArgs e)

   {

       // Populate series data

       Random random = new Random();

       for (int pointIndex = 0; pointIndex < 10; pointIndex++)

       {

           Chart1.Series["Series1"].Points.AddY(random.Next(45, 95));

       }

       // Set chart type

       Chart1.Series["Series1"].ChartType = SeriesChartType.StackedArea100;

       // Show point labels

       Chart1.Series["Series1"].IsValueShownAsLabel = true;

       // Disable X axis margin

       Chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = false;

       // Enable 3D

       Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

       //// Set the first two series to be grouped into Group

       Chart1.Series["LightBlue"]["StackedGroupName"] = "Group1";

       Chart1.Series["Gold"]["StackedGroupName"] = "Group1";

       //// Set the last two series to be grouped into Group2

       Chart1.Series["Red"]["StackedGroupName"] = "Group2";

       Chart1.Series["DarkBlue"]["StackedGroupName"] = "Group2";

   }

}

HTML SOURCE

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "www.w3.org/.../xhtml1-transitional.dtd">

<html xmlns="www.w3.org/.../xhtml">

<head runat="server">

   <title>Untitled Page</title>

</head>

<body>

   <form id="form1" runat="server">

   <div>

       <asp:Chart ID="Chart1" runat="server">

           <Legends>

               <asp:Legend Name="Legend1">

               </asp:Legend>

           </Legends>

           <Titles>

               <asp:Title Name="Title1">

               </asp:Title>

           </Titles>

            <Series>

        <asp:Series Name="Series1" ChartType="StackedBar100" ></asp:Series>

    </Series>

           <MapAreas>

               <asp:MapArea Coordinates="0,0,0,0" />

           </MapAreas>

           <ChartAreas>

               <asp:ChartArea Name="ChartArea1">

               </asp:ChartArea>

           </ChartAreas>

       </asp:Chart>

   </div>

   </form>

</body>

</html>

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Friday, March 26, 2010 12:54 PM by Sliceco

Excellent article. Needed to know how to dynamically edit the Legends and this was an excellent source. Thanks!

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Tuesday, April 20, 2010 10:30 AM by Suthish Nair

### venkysmv85 ###

Sorry for late reply...

Its simple, you are not adding the new Series into SeriesCollection list.

You must add the new Series, you can do it in two ways..

1. (.aspx)

<Series>

  <asp:Series Name="Series1" ChartType="StackedBar100"></asp:Series>

  <asp:Series Name="LightBlue"></asp:Series>

  <asp:Series Name="Gold"></asp:Series>

  <asp:Series Name="Red"></asp:Series>

  <asp:Series Name="DarkBlue"></asp:Series>

 </Series>

2. (codebehind)

Chart1.Series.Add("LightBlue");

Chart1.Series["LightBlue"]["StackedGroupName"] = "Group1";

Chart1.Series.Add("Gold");

Chart1.Series["Gold"]["StackedGroupName"] = "Group1";

//// Set the last two series to be grouped into Group2

Chart1.Series.Add("Red");

Chart1.Series["Red"]["StackedGroupName"] = "Group2";

Chart1.Series.Add("DarkBlue");

Chart1.Series["DarkBlue"]["StackedGroupName"] = "Group2";

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Tuesday, May 04, 2010 10:07 AM by nagaraju

thanks..this code helped me a lot..in advance...i need some clarification..how can i display the percentages on the output of pie chart instead of values..plz help me..

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Wednesday, July 07, 2010 6:49 PM by Joshua

With the sample provided how would you bind the Xaxis to col 3

(series)       (yaxis)      (xaxis)

col 1          col 2        col 3

team a         500.00       7/1/2010

team b         475.00       7/1/2010

team a         300.00       7/2/2010

team b         375.00       7/2/2010

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Monday, August 02, 2010 1:40 PM by sinedyip

Thanks for the example.

I have a problem.

I have a chart with percentage on Y and letters on X and it plot a lot of bars with different colors using: ReportChart.Series["Series1"].Palette = ChartColorPalette.BrightPastel.

Now I want to crate a legend for these bars using my data in my database and I don't  know how. I am using only one serie.

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Tuesday, August 17, 2010 6:47 AM by Suthish Nair

sorry for late reply..

try setting..

ReportChart.Series["Units"].IsVisibleInLegend = true;

# Mschart - VB-MUNDO - Programacion Visual

Tuesday, September 14, 2010 2:03 PM by Mschart - VB-MUNDO - Programacion Visual

Pingback from  Mschart - VB-MUNDO - Programacion Visual

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Friday, October 01, 2010 6:33 AM by karthik

Tooltip is not working..can u provide some example with working copy..

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Monday, October 04, 2010 11:42 AM by Suthish Nair

refer article:

www.c-sharpcorner.com/.../Default.aspx

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Thursday, December 02, 2010 12:09 AM by khehra

best solution

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Monday, April 11, 2011 12:07 PM by rolly

how make the legend position to bottom in code behind.

# re: MSChart - Dynamic assign ChartArea, Series, Legends etc..

Saturday, September 24, 2011 8:56 AM by prashant

hey hi i m new to MScharts..i want to know the difference between the lines-

1)Charts1.Series["default"].color=------

2)series.Color=----

i know v r we r creating a new Series list "Default"....v can use "series1" so y "default" wid more lines to write...can u plz xplain me more

Leave a Comment

(required) 
(required) 
(optional)
(required)