Search This Blog

Translate

Saturday, May 25, 2013

MS Chart Control : Create user control of chart control.

Get real time news update from your favorite websites.
Don't miss any news about your favorite topic.
Personalize your app.

Check out NTyles.


Get it on....

NTyles-App





In my previous post DataVisualization with Chart Control I show you how to use MS Chart Control for data visualization and some of its features. In this post I will show you how to make a chart user control. Chart user control can be very handy when you have multiple pages that will access the same control and you want the output accordingly. According to the MSDN a user control is :

 "
In addition to using Web server controls in your ASP.NET Web pages, you can create your own custom, reusable controls using the same techniques you use for creating ASP.NET Web pages. These controls are called user controls.
A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit.
"
                                                              -

User Control is a very powerful feature of .NET FRAMEWORK.
I have below described how to make a user control , add a chart control to it and use it in your web pages. Here are the steps on how to create a chart user control.

STEP 1: Add a web user control in your project.
  1. First left click on the project in which you want to add a user control as shown in Figure 1.
  2. Choose Add New Item and from web template choose web user control , give a suitable name and click add as shown in Figure 1.2.
  3. Now add a chart control from a toolbox to the user control as shown in Figure 1.3.
  4. Then configure data source of your chart. If you don't know how to configure data source then please check out Cofigure Data Source.
Figure 1 : Add a new item.



Figure 1.2 : Choose a "Web User Control"


Figure : 1.3 : Add a chart Control to a web user control.


Upto this step the script should like (ChartUserControl.ascx) :
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ChartUserControl.ascx.cs" Inherits="ChartUserControl.ChartUserControl" %>
<%@ Register assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.UI.DataVisualization.Charting" tagprefix="asp" %>
<asp:Chart ID="userControlChart" runat="server" Height="408px" Width="686px" DataSourceID="Heights">
    <series>
        <asp:Series Name="Series1" XValueMember="name" YValueMembers="height"> </asp:Series>
    </series>
    <chartareas>
        <asp:ChartArea Name="userControlChartArea">
        </asp:ChartArea>
    </chartareas>
    <Legends>
        <asp:Legend Name="ChartLegend">
        </asp:Legend>
    </Legends>
    <Titles>
        <asp:Title Name="ucFinalTitle">
        </asp:Title>
    </Titles>
</asp:Chart>

<asp:SqlDataSource ID="Heights" runat="server"
    ConnectionString="<%$ ConnectionStrings:ConnectionString %>
" SelectCommand="SELECT [name], [height] FROM [Heights]">
</asp:SqlDataSource>

Now add the variables for controls that you want to the chart. These are those controls that are set and get from other web pages, from which you want to access the chart user control. So below is the code snippet of the control that I have added to control the behaviour of the chart user control. If you guys want to add more controls then go on adding variables and manipulate them.
//CharUserControl.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.DataVisualization.Charting;

namespace ChartUserControl
{
    public partial class ChartUserControl : System.Web.UI.UserControl
    {
        /// 
        /// Defining all the properties of chart that you want to control.
        /// You may add or remove the properties which you are not willing to use.    
        /// 
        /// 
        /// 
        public String  ChartTitle { get; set; }
        public String  ChartTypeofchart { get; set; }
        public String  ChartName { get; set; }
        public String  ChartBackGroundColor { get; set; }
        public String  ChartSeriesColor { get; set; }
        public String  xaxistitle { get; set; }
        public String  yaxistitle { get; set; }
        public Boolean enable3d { get; set; }
        public Boolean enablelegend { get; set; }
        public int     xaxisinterval { get; set; }
        public String  legendtitle { get; set; }
        public String  xaxisvaluemember { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            userControlChart.ViewStateMode = System.Web.UI.ViewStateMode.Enabled;
        }

        public void createChart()
        {

            //sets the chart title
            userControlChart.Titles["ucFinalTitle"].Text = ChartTitle;
            //for enalbling the legend
            userControlChart.Legends["ChartLegend"].Enabled = true;
            userControlChart.Series["Series1"].LegendText = legendtitle;
            //set axis interval
            userControlChart.ChartAreas["userControlChartArea"].AxisX.Interval = xaxisinterval;
            //Type Of Chart
            #region chartType Region
            if (ChartTypeofchart == "Column")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.Column;
            if (ChartTypeofchart == "Bar")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.Bar;
            if (ChartTypeofchart == "Stacked")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.StackedBar;
            if (ChartTypeofchart == "Pie")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.Pie;
            if (ChartTypeofchart == "Area")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.Area;
            if (ChartTypeofchart == "BoxPlot")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.BoxPlot;
            if (ChartTypeofchart == "Line")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.Line;
            if (ChartTypeofchart == "Point")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.Point;
            if (ChartTypeofchart == "Spline")
                userControlChart.Series["Series1"].ChartType = SeriesChartType.Spline;
            #endregion
            #region Axis Titles
            //value shown as label
            userControlChart.Series["Series1"].IsValueShownAsLabel = true;
            //xaxis title
            userControlChart.ChartAreas["userControlChartArea"].Axes[0].Title = xaxistitle;
            //yaxis title
            userControlChart.ChartAreas["userControlChartArea"].Axes[1].Title = yaxistitle;
            #endregion
            #region legend text
            //Legend Text
            userControlChart.Series["Series1"].LegendText = xaxisvaluemember;
            #endregion
            #region chart BackGround color
            if (ChartBackGroundColor == "Black")
                userControlChart.BackColor = System.Drawing.Color.Black;
            if (ChartBackGroundColor == "Blue")
                userControlChart.BackColor = System.Drawing.Color.Blue;
            if (ChartBackGroundColor == "Green")
                userControlChart.BackColor = System.Drawing.Color.Green;
            if (ChartBackGroundColor == "Red")
                userControlChart.BackColor = System.Drawing.Color.Red;
            if (ChartBackGroundColor == "Yellow")
                userControlChart.BackColor = System.Drawing.Color.Yellow;
            if (ChartBackGroundColor == "Pink")
                userControlChart.BackColor = System.Drawing.Color.Pink;
            if (ChartBackGroundColor == "AliceBlue")
                userControlChart.BackColor = System.Drawing.Color.AliceBlue;
            if (ChartBackGroundColor == "Aqua")
                userControlChart.BackColor = System.Drawing.Color.Aqua;
            if (ChartBackGroundColor == "Aquamarine")
                userControlChart.BackColor = System.Drawing.Color.Aquamarine;
            if (ChartBackGroundColor == "Brown")
                userControlChart.BackColor = System.Drawing.Color.Brown;
            if (ChartBackGroundColor == "Chocolate")
                userControlChart.BackColor = System.Drawing.Color.Chocolate;
            if (ChartBackGroundColor == "DarkBlue")
                userControlChart.BackColor = System.Drawing.Color.DarkBlue;
            if (ChartBackGroundColor == "DarkCyan")
                userControlChart.BackColor = System.Drawing.Color.DarkCyan;
            if (ChartBackGroundColor == "Darkviolet")
                userControlChart.BackColor = System.Drawing.Color.DarkViolet;
            if (ChartBackGroundColor == "Ivory")
                userControlChart.BackColor = System.Drawing.Color.Ivory;
            if (ChartBackGroundColor == "Azure")
                userControlChart.BackColor = System.Drawing.Color.Azure;
            if (ChartBackGroundColor == "DimGray")
                userControlChart.BackColor = System.Drawing.Color.DimGray;
            userControlChart.ChartAreas["userControlChartArea"].BackColor = System.Drawing.Color.AliceBlue;
            #endregion
            #region chart Series Color

            if (ChartSeriesColor == "Black")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Black;
            if (ChartSeriesColor == "Blue")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Blue;
            if (ChartSeriesColor == "Green")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Green;
            if (ChartSeriesColor == "Red")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Red;
            if (ChartSeriesColor == "Yellow")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Yellow;
            if (ChartSeriesColor == "Pink")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Pink;
            if (ChartSeriesColor == "AliceBlue")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.AliceBlue;
            if (ChartSeriesColor == "Aqua")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Aqua;
            if (ChartSeriesColor == "Aquamarine")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Aquamarine;
            if (ChartSeriesColor == "Brown")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Brown;
            if (ChartSeriesColor == "Chocolate")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Chocolate;
            if (ChartSeriesColor == "DarkBlue")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.DarkBlue;
            if (ChartSeriesColor == "DarkCyan")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.DarkCyan;
            if (ChartSeriesColor == "Darkviolet")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.DarkViolet;
            if (ChartSeriesColor == "Ivory")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Ivory;
            if (ChartSeriesColor == "Azure")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.Azure;
            if (ChartSeriesColor == "DimGray")
                userControlChart.Series["Series1"].Color = System.Drawing.Color.DimGray;
            #endregion
            #region Enable 3D
            userControlChart.ChartAreas["userControlChartArea"].Area3DStyle.Enable3D = enable3d;
            #endregion
            #region enableLegend
            userControlChart.Legends["ChartLegend"].Enabled = enablelegend;
            #endregion
            ///Enable viewing            
            userControlChart.EnableViewState = true;
        }
    }
}
STEP 2: Edit web.config.
  1. Open web.config and add :
     <add src="~/ChartUserControl.ascx" tagname="ucChartUserControl" tagprefix="uc" />
     
    inside <Controls>  <Controls/>
    
The script in web.config should look like this:
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting"
          assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
          <add tagPrefix="uc" tagName="ucChartUserControl" src="~/ChartUserControl.ascx" />
      </controls>
    </pages>
STEP 3: Add user control to the pages in which you want the controls
  1. Identify the location where you want to display your chart.
  2. From Solution explorer click on the ChartUserControl.ascx and drag it to the location in your web page where you want to display the chart. In my case I have added two control in the page Demo1.aspx as shown in Figure 3.1. After you drag and drop your usercontrol in the design view then .net will generate script in your source view as below:
     <uc:ucChartUserControl ID="ucChartUserControl1" runat="server" />
    
Figure 3.1 : Drag and Drop user control to desired pages.

In my case I have added two user control in the same page and a button for controlling the user controls. The source view of my demo1.aspx is as below :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Demo1.aspx.cs" Inherits="ChartUserControl.ChartDemos.Demo1"
    MasterPageFile="~/Site.Master" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div>
        <div>
            <div>
                <uc:ucChartUserControl ID="ucChartUserControl1" runat="server" />
            </div>
            <div>
                <uc:ucChartUserControl ID="ucChartUserControl2" runat="server" />
            </div>
        </div>
        <div>
            <asp:Button ID="Button1" runat="server" Text="Change Chart" OnClick="changeChart" />
        </div>
    </div>
</asp:Content>
STEP 4 : Control User Control behaviour I am firing an event from my asp button that will change the color, name, legend 3d style and many more. Here's the code (Demo1.aspx.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ChartUserControl.ChartDemos
{
    public partial class Demo1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void changeChart(object sender, EventArgs e)
        {
            setFirstChart();
            setSecondChart();
        }

        public void setFirstChart()
        {
            ucChartUserControl1.ChartSeriesColor = "Red";
            ucChartUserControl1.ChartTitle = "This is demo of chart user control";
            ucChartUserControl1.ChartTypeofchart = "Bar";
            ucChartUserControl1.ChartName = "UserControlChart";
            ucChartUserControl1.ChartBackGroundColor = "Yellow";
            ucChartUserControl1.xaxistitle = "Name";
            ucChartUserControl1.yaxistitle = "Height";
            ucChartUserControl1.xaxisvaluemember = "Name";
            ucChartUserControl1.enable3d = true;
            ucChartUserControl1.enablelegend = true;
            ucChartUserControl1.legendtitle = "Rambo Legend";
            ucChartUserControl1.xaxisinterval = 1;
            ucChartUserControl1.createChart();
        }

        public void setSecondChart()
        {
            ucChartUserControl2.ChartSeriesColor = "Black";
            ucChartUserControl2.ChartTitle = "This is demo of chart user control 2";
            ucChartUserControl2.ChartTypeofchart = "Pie";
            ucChartUserControl2.ChartName = "UserControlChart 2";
            ucChartUserControl2.ChartBackGroundColor = "Blue";
            ucChartUserControl2.xaxistitle = "Name";
            ucChartUserControl2.yaxistitle = "Height";
            ucChartUserControl2.xaxisvaluemember = "Name";
            ucChartUserControl2.enable3d = false;
            ucChartUserControl2.enablelegend = true;
            ucChartUserControl2.legendtitle = "Rambo Spline Legend";
            ucChartUserControl2.xaxisinterval = 1;
            ucChartUserControl2.createChart();
        }
    }
}
All done now, run your code and analyse the output: I am showing you the output in my case (I am good designer and am a good liar too):
Figure 4.1 : Demo 1.

 and after clicking button:
Figure 4.2 : Final output.

 Please if you have any confusion don't forget to reach out to me.

No comments:

Post a Comment