Create Charts with Asp.net and C#



Introduction :
      Hi, Here I will Explain how to create the Charts that looks as a Dashboard,The Charts created here is pure Asp chart, no third party tools used here.System.Web.UI.DataVisualization.Charting  is the namespace used in Aspx page PageDirective to-access the Charting concept.

Steps to follow

  1. Create the Database,table and add Data to it.
  2. Create Aspx page.
  3. Add Page Directive  to the Created Aspx page.
  4. Change the settings in Web.config file as listed below.
  5. Bind the Data to the Chart and XY values to the Chart with the Series.
step 1 :



step 2 & 3 :

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

<!DOCTYPE html>
<html>
<head runat="server">
<title>Fourthbottle</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:center">
<asp:Chart ID="Chart1" Width="293px"  Height="299px" runat="server" >
<Series>
<asp:Series ChartType="Bar" Name="Series1" Legend="Legend1">
</asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Area3DStyle-Enable3D="true" Name="ChartArea1">
<Area3DStyle Enable3D="True"></Area3DStyle>
</asp:ChartArea>
</ChartAreas>
</asp:Chart>
</div>
</form>
</body>
</html>

step 4 : Add the below code to your web.config file under <system.websection.

<system.web>
    <httpHandlers>
      <add path="ChartImg.axd" verb="GET,HEAD,POST" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false" />
    </httpHandlers>
    <pages>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI.DataVisualization.Charting" assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      </controls>
    </pages>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
    </compilation>
. . . . . .  .
 . . . . . . .
</system.web>

step 5 :  Your C# code follows as below.

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.Data.SqlClient;

namespace WebApplication1
{
public partial class Page1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source= your connection String");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from table1", con);
DataSet ds = new DataSet();
da.Fill(ds);
Chart1.DataSource = ds;
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
 {
Chart1.Series["Series1"].Points.AddXY(ds.Tables[0].Rows[i]["Name"], ds.Tables[0].Rows[i]["Attendence"]);
 }
 }
 }
}