Search This Blog

Translate

Showing posts with label MS Chart Control. Show all posts
Showing posts with label MS Chart Control. Show all posts

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.

Monday, February 11, 2013

MS Chart Control : Data Visualization with MS 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 I told you guys why MS Chart Control is a very cool API for data visualization in asp.net.  In my series of posts, I will show you how to get on with the MS Chart Control. My post is generally for beginners who really want to make something out of data visualization. In this post I will show you how to first make a column chart using MS Chart Control.
So without further ado let me guide you to the way to the success for creating a chart in asp.net using Visual c sharp in Microsoft’s Visual Studio 2010.

Step 1 :  Create a new web application Project (ASP.NET and Visual C#).
First of all create a new web application in asp.net and visual c# in Visual Studio 2010. If you guys know how to create a web application project in VS 2010 then you can skip this section.

1.       Open Visual Studio 2010.
2.       Go to File -> New Project. You will be welcomed by following window.

1. Create a new web project .
3.       Choose ASP.NET web application with Visual C#.
4.       Give name and location and solution name to your project and click OK.

Step 2 : Add a chart control to your web page.

2. Welcome Screen after you create a web project
By default you will be welcomed with the Design view as shown in figure 2 which is a default template. If you to want to use your own template then you’re always welcome. Chart Control can be directly drag and dropped to the desing view but what I suggest is to use source view for drag and dropping because from here you can manage your code and you can also give '<div></div>' tags for CSS insertions, hehe , in the project. This really makes your source view manageable. But mine is not the only way, you can follow whatever method you want to follow. Now here are the step how to add a chart control to your source view.
  1.  Go to the source view.
  2.   Drag and drop the ‘Chart’ tool from the Toolbox, the chart tool is shown in fig 3.
3. Add a chart control to source view.



Step 3: Make some data to test on.
Now you added a chart. But your chart control needs data to display the chart upon. So, here I am creating a test data in MS SQL Server. If you already have data which you want to visualize then you can use them too. Here I am showing you how to build a sql server table and insert some data in to it.
  1.  Open solution explorer window.
  2.  Left Click on App_Data -> Add -> New Item shown in fig 4.
  3. Select SQL Server Database and Click Next.
  4. Now open Server Explorer. Unfold the SortDemo.mdf icon as shown in fig 5.
  5. Left click on Tables and Choose Add New Table.
  6. Define table constraints and data structure, for example take a look at fig 6..
  7. Left click on new formed tables and choose ‘Show Table Data’ as shown in fig 7.
  8. Now insert some data in table as shown in fig 8.
4. Add a new item demo.
5. Add a new table.

6. Define table.

7. Show table data.



8. Insert data into table.
Till now you created a data source in a Sql Server database, added a chart control in the source view. Now lets add that data source to the chart control.

Step 3 : Assign data to the chart
  1.  Go to the 'Design view'.
  2. Click on the chart area. You will see a small arrow like icon.
  3. Click on that icon. A small chart Tasks area will appear as shown in fig 9.
  4.  From  Data Source Drop Down menu choose <New Data Source>.
  5. Then Data Source Configuration Wizard appears as shown in fig 10.
  6. Choose ‘SQL Database’ and give a name for the Data Source and Click OK as shown in fig 11.
  7.  If you want to save the connection String then save it or just Click Next > as shown in fig 12.
  8. Check the checkbox that shows  ‘* ‘ and Click Next > as shown in fig 13.
  9. Test. If everything is 'ok' then click Finish as shown in fig 14.
9. Assign data source to chart - 1.

10. Assign data source to chart - 2.

11 . Assign data source to chart - 3.

12. Assign data source to chart - 4.

13 . Assign data source to chart - 5.

14 . Assign data source to chart - 6.

15 . Assign data source to chart - 7.

16 . Assign data source to chart - 8.
Step 4: Give data to the chart, data of which you want to generate chart.
  1.  From Chart Type Drop Down Menu choose the type of chart which you want to display. Here I am choosing Column chart as shown in fig 15.  You can also choose other chart types too like :
      1. Pie
      2. Bar
      3. Doughnut
      4. Spline
      5. Stacked
  2.  Assign data members to x-axis and y-axis. Choose X Value Member and Y Value Members as shown in fig 16.
Now you’re done. Click on Debug -> Start without Debugging. And if everything is ok you will be welcomed by following web page as shown in fig 17.
17. Chart Demo


Have fun with this cool api. In my next post I will show you some cool features of MS Chart Control using the code behind.

Monday, January 28, 2013

MS Chart Control, A DataVisualization API

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 I shared some of the quotations which changed my life which I present as a refreshment. Now in this post I will show why MS-Chart Control is a good api for Data Visualization for .NET.

During my internship in one of the reputed company , 'Nepasoft Solutions Pvt. Ltd', I did a project in DATA VISUALIZATION AND FILTERING SYSTEM with other five genius guys from my college. In that project my role was to visualize the data. The project was in ASP.NET and C SHARP. I goggled for some cool API's and I found that MS-Chart control would be the best choice for our project. I found it very helpful and it has a very good documentation too.

Some of the good features I found in this API's are :
  • Chart customization features from code also.
  • Simple linkage with the database.
  • Fabulous documentation
  • Sorting, Aggregatem, Analytic etc functions.
  • 3D customization, colors different models and many others/
  • Trend Analysis
  • Many graphing and visualizations tools from pie chart to splines and many more.
  • Easy aggregation with back end.
  • ASP.Net's user control feature makes the chart control more powerful and user-friendly.
In my next blog I will show you some cool features of chart control with videos and code :), which you guys would surely find helpful. Till then do some research of your own. Let me know if you guys have any queries regarding MS-chart control.