How to use Chart Controls in ASP.NET

No.of Views1224
Bookmarked0 times
Downloads 
Votes0
By  Bharat   On  20 Nov 2010 01:11:31
Tag : ASP.NET , Charts
In this article, i will explain how to use the chart control in ASP.NET.Specially bind data to charts controls.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article, i will explain how to use the chart control in ASP.NET.Specially bind data to charts controls.Before we play with Chart control in ASP.NET, we have to download the Charts controls from Microsoft.Because Charts does not come with inbuilt in existing .NET  framework.

Download Charts Controls

if you are does not downloaded Charts controls earlier,You can download from http://www.microsoft.com/downloads/en/details.aspx?FamilyId=130F7986-BF49-4FE5-9CA8-910AE6EA442C&displaylang=en

Implementation

If you have downloaded the control and install. then you have to add the charts control assembly to toolbox in order to use in your page.as like following, 

Image Loading

Once you add charts library into the toolbox, it will be like follwoing, 

Image Loading

Then just drag and drop chart control in page, it can be like,

HTML Code

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

<%@ Register Assembly="System.Web.DataVisualization, Version=3.5.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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Chart ID="Chart1" runat="server" Palette="None" Width="818px" Height="400px"
        ImageStorageMode="UseImageLocation">
        <Series>
            <asp:Series Name="Series1" ChartArea="ChartArea1" YValuesPerPoint="6" ChartType="Bubble">
            </asp:Series>
        </Series>
        <ChartAreas>
            <asp:ChartArea Name="ChartArea1">
                <Area3DStyle Enable3D="True" LightStyle="Realistic" Rotation="20" WallWidth="5" />               
            </asp:ChartArea>
        </ChartAreas>
    </asp:Chart>
    </form>
</body>
</html>

In chart control, there is two important sections.

  1. Series:This represent the chart data series
  2. ChartAreas : This is represent chart type and how is going to show in page.

Just create a simple database and store data for chart.

Sql Script to create table

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbStudentMCQRecord]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tbStudentMCQRecord](
      [id] [bigint] IDENTITY(1,1) NOT NULL,
      [studentid] [varchar](50) NULL,
      [classid] [bigint] NULL,
      [topicid] [bigint] NULL,
      [starttime] [datetime] NULL,
      [endtime] [datetime] NULL,
      [totalquestion] [int] NULL,
      [totalattempt] [int] NULL,
      [wronganswer] [int] NULL,
      [correctanswer] [int] NULL,
      [result_avg] [decimal](18, 2) NULL,
 CONSTRAINT [PK_tbStudentMCQRecord_1] 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]
END

Now lets write simple code to get the data from the database and then Bind to Chart.

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.SqlClient;
using System.Configuration;
using System.Web.UI.DataVisualization.Charting;
using System.Data;

public partial class Studentportal_chart : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection();protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
        con.Open();
        SqlDataAdapter adp = new SqlDataAdapter(@"select top(7) tbStudentMCQRecord.id, tbTopics.id,tbTopics.topic,
tbStudentMCQRecord.studentid, tbStudentMCQRecord.result_avg,tbStudentMCQRecord.starttime,
convert(varchar, tbStudentMCQRecord.starttime, 100)as date
from tbStudentMCQRecord
order by tbStudentMCQRecord.id desc"
, ConfigurationManager.ConnectionStrings["cnn"].ConnectionString); adp.SelectCommand.Parameters.Add("@studentid", SqlDbType.VarChar, 50).Value = Session["sid"].ToString(); adp.SelectCommand.Parameters.Add("@topicid", SqlDbType.Int).Value = Convert.ToInt32(Session["topicid"]); DataSet ds = new DataSet(); adp.Fill(ds); Chart1.DataSource = adp; Chart1.Series["Series1"].XValueMember = "date"; Chart1.Series["Series1"].YValueMembers = "result_avg"; con.Close(); Chart1.DataBind(); adp.Dispose(); } }

 That's all. now run application, if you have records in table, you will see the chart in page.

Download Sample Project

Download source files -3 kb

Conclusion

Through this article, i have show how to create chart using Microsoft Chart Library in ASP.NET, even dynamically Bind Data to chart from the Database.

 
Sign Up to vote for this article
 
About Author
 
Bharat
Occupation-Software Engineer
Company-Espranza
Member Type-Junior
Location-India
Joined date-13 Nov 2010
Home Page-
Blog Page-http://usingaspdotnet.blogspot.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top