Tuesday, 25 June 2013

Create Line Chart using asp.net

C# code:
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 WebApplication3
{
    public partial class WebForm5 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
            Chart1.Series["Series1"].ChartType = SeriesChartType.Line;
        Chart1.Series["Series1"]["DrawingStyle"] = "Emboss";

       
        Chart1.Series["Series1"].IsValueShownAsLabel = true;
     
        DataTable dt = new DataTable();    
        dt.Columns.Add("Id", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Age", typeof(string));
        dt.Columns.Add("Date", typeof(DateTime));

        //
        // Here we add five DataRows.
        //
        dt.Rows.Add(0, "k7", "0", DateTime.Now);
        dt.Rows.Add(10, "simbu", "10", DateTime.Now);
        dt.Rows.Add(12, "hari", "15", DateTime.Now);
        dt.Rows.Add(15, "lax", "20", DateTime.Now);
        dt.Rows.Add(20, "ram", "25", DateTime.Now);
        dt.Rows.Add(100, "vijay", "29", DateTime.Now);

        Chart1.DataSource = dt;
        Chart1.Series["Series1"].XValueMember = "Name";
        Chart1.Series["Series1"].YValueMembers = "Age";
        Chart1.DataBind();


        }
    }
}


aspx code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm5.aspx.cs" Inherits="WebApplication3.WebForm5" %>
<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Chart ID="Chart1" runat="server" Height="400px" Width="500px" BorderDashStyle="Solid"
            BackSecondaryColor="White" BackGradientStyle="TopBottom" BorderWidth="8px" BackColor="211, 223, 240"
            BorderColor="#1A3B69" BorderlineWidth="3">
            <Titles>
                <asp:Title Text="Title of the Graph comes here" />
            </Titles>
            <Series>
                <asp:Series Name="Series1" BorderColor="180, 26, 59, 105">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1" BorderColor="64, 64, 64, 64" BorderDashStyle="Solid"
                    BackSecondaryColor="White" BackColor="64, 165, 191, 228" ShadowColor="Transparent"
                    BackGradientStyle="TopBottom">
                    <Area3DStyle Rotation="10" Perspective="10" Inclination="15" IsRightAngleAxes="False"
                        WallWidth="0" IsClustered="False"></Area3DStyle>
                    <AxisY LineColor="64, 64, 64, 64">
                        <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
                        <MajorGrid LineColor="90, 90, 90, 90" />
                    </AxisY>
                    <AxisX LineColor="64, 64, 64, 64">
                        <LabelStyle Font="Trebuchet MS, 8.25pt, style=Bold" />
                        <MajorGrid LineColor="90, 90, 90, 90" />
                    </AxisX>
                </asp:ChartArea>
            </ChartAreas>
        </asp:Chart>
    </div>
    </form>
</body>
</html>

Line Graph:


Monday, 24 June 2013

LINE CHART USING ASP.NET WITH SQL-SERVER


Using Sql Server:
CREATE TABLE [dbo].[tblChart](      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [year] [varchar](50) NULL,
      [sales] [varchar](50) NULL,
      [expences] [varchar](50) NULL,
 CONSTRAINT [PK_tblChart] PRIMARY KEY CLUSTERED(      [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

SET IDENTITY_INSERT [dbo].[tblChart] ON
INSERT [dbo].[tblChart] ([id], [year], [sales], [expences]) VALUES (1, N'2009', N'5000', N'2136')
INSERT [dbo].[tblChart] ([id], [year], [sales], [expences]) VALUES (2, N'2010', N'9002', N'5063')
INSERT [dbo].[tblChart] ([id], [year], [sales], [expences]) VALUES (3, N'2011', N'8800', N'2225')
SET IDENTITY_INSERT [dbo].[tblChart] OFF


In .aspx Page:
<head id="Head1" runat="server">
    <title>Line Chart </title>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Literal ID="lt" runat="server"></asp:Literal>
    </div>
    <div id="divLineChart"></div>
    </form>
</body>


In .aspx.cs Page:
  SqlConnection Conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    StringBuilder str = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
        Conn.Open();
        if (!IsPostBack)
        {
            bindChart();
        }
    }
    private void bindChart()
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from tblChart", Conn);
        DataTable dt = new DataTable();
        try
        {
            da.Fill(dt);
            // This code write in javascript code in .aspx page..
            // and we can write in code page also..
            // this code i am catching in the stringbuilder class

            //data.addColumn('string'(datatype), 'Year'(columnname according to the sql table));
            //data.addColumn('number'(datatype), 'Sales'(columnname according to the sql table));
            //data.addColumn('number'(datatype), 'Expenses'(columnname according to the sql table));

            // This data is coming from the sql server
            str.Append(@"<script type=text/javascript> google.load( *visualization*, *1*, {packages:[*corechart*]});
                google.setOnLoadCallback(drawChart);
                function drawChart() {
               
                    var data = new google.visualization.DataTable();
                    data.addColumn('string', 'Year');
                    data.addColumn('number', 'Sales');
                    data.addColumn('number', 'Expenses');
                    data.addRows(" + dt.Rows.Count + ");");
           
            Int32 i;
            for (i = 0; i <= dt.Rows.Count - 1; i++)
            {
                str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i]["year"].ToString() + "');");
                str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["sales"].ToString() + ") ;");
                str.Append(" data.setValue(" + i + "," + 2 + "," + dt.Rows[i]["expences"].ToString() + ");");
            }
            str.Append("var chart = new google.visualization.LineChart(document.getElementById('divLineChart'));");
            str.Append("chart.draw(data, {width: 650, height: 300, legend: 'bottom',is3D: false,title: 'Performance',");
            str.Append("vAxis: {title: 'Year', titleTextStyle: {color: 'green'}}");
            str.Append("}); }");
            str.Append("</script>");

            lt.Text = str.ToString().TrimEnd(',').Replace('*', '"');
            Conn.Close();
        }
        catch
        {  }
        finally
        {Conn.Close();}
    }