Small Project on How to use the Chart Control in ASP.NET?

Raj.Trivedi
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 10909 red flag
Rating: 4.5 out of 5  
 2 vote(s)

In this article we will see how we can use the Chart Control in asp.net.

Today we will be inserting,searching and deleting data in the Application and checking how the results are shown in Graphical View.

Introduction


In this article we will see how we can implement ASP.NET Chart Control.The chart control allows us to give Graphical representation of the data we want to show to the user.


Objective


  1. Understanding the Chart Control.
  2. Binding data to the Chart Control.

Using the code



  1. Open Visual Studio -> Create a New Empty Web site.
  2. Add 1 Web form as SampleChart in the page.
  3. Now Drag and drop total 4 Textboxes, 4 buttons, 2 Literal.
  4. Now drag and drop a Grid and a Chart control from the Toolbox under the data toolbox.
  5. Your UI Should be like in the Screen Shot.

Screen





Explanation of the Chart Control.

  1. The Chart Control has 2 important properties i.e. Series and Chart Area.
  2. Series allows you to define the X and Y axis member to display the chart.
  3. The X Value member is the range and Y value member is the actual value for the range.
  4. In this article we are visualizing the strength of population year wise
  5. So the X member will Year and the Y value member will be the value.
  6. The chart area is the area that will display the chart as per the data coming from the database.


Explanation of the Application.

  1. In this application we will first enter month and the value of the population.
  2. Once we enter the data in the database the data will bind it to the grid.
  3. The same data will be bounded to the Chart Control and show it in the Bar Diagram.
  4. We can also change the view of the chart by changing the Chart Type.
  5. Chart Type can be changed by clicking the arrow on top corner of the Chart Control.Check the screen.
  6. To update the data you have to enter the name of the month and update the value and also you can delete it.

Changing the View of the Chart







Final Output









// Database Table
create table Marks
(

ID int identity(1,1),
Months varchar(15),
Population int
)
// HTML Mark up and Code behind
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ChartSample.aspx.cs" Inherits="ChartSample" %>

<%@ 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 runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 107%;
            height: 157px;
        }
        .style3
        {
        }
        .style5
        {
        }
        .style6
        {
        }
        .style7
        {
            font-family: Algerian;
            font-size: large;
        }
        .style8
        {
            font-family: Algerian;
            font-size: medium;
        }
        .style10
        {
            width: 110px;
        }
        .style11
        {
            width: 178px;
        }
        .style12
        {
            width: 134px;
        }
        .style13
        {
            font-family: Algerian;
            font-size: x-large;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center" class="style13">

    Chart Sample : With Insert,Update and Delete
    <br />
    <br />
    
    </div>
    <div>
    
        <table class="style1">
            <tr>
                <td class="style7" colspan="2">
                    Add New Record</td>
                <td class="style10">
                    &nbsp;</td>
                <td class="style8" colspan="3">
                    Search Record : Here you can Update the Record and Also Delete</td>
            </tr>
            <tr>
                <td class="style3">
                    Enter Month
                </td>
                <td class="style12">
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
                <td class="style10">
                    &nbsp;</td>
                <td class="style5">
                    Enter Month
                </td>
                <td class="style6" colspan="2">
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox> &nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
                &nbsp;
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Enter Population Figure
                </td>
                <td class="style12">
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
                <td class="style10">
                    &nbsp;</td>
                <td class="style5">
                    Change Population Figure
                </td>
                <td class="style6">
                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                </td>
                <td class="style11">
                    &nbsp;
                </td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;
                </td>
                <td class="style12">
                    <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
                </td>
                <td class="style10">
                    &nbsp;
                </td>
                <td class="style5">
                    &nbsp;
                </td>
                <td class="style6" colspan="2">
                    <asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
                </td>
            </tr>
            <tr>
                <td class="style3">
                    &nbsp;
                </td>
                <td class="style12">
                    <asp:Literal ID="litdesc" Visible="false" runat="server"></asp:Literal>
                </td>
                <td class="style10">
                    &nbsp;
                </td>
                <td class="style5">
                    &nbsp;
                </td>
                <td class="style6">
                    <asp:Literal ID="litupdate" Visible="false" runat="server"></asp:Literal>
                </td>
                <td class="style11">
                    &nbsp;
                </td>
            </tr>
        </table>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <div align="center">
            <asp:GridView ID="xPopulationData" runat="server" AutoGenerateColumns="False" 
                Width="384px" BackColor="White" BorderColor="#3366CC" BorderStyle="None" 
                BorderWidth="1px" CellPadding="4">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" Visible="False" />
                    <asp:BoundField DataField="Months" HeaderText="Month" />
                    <asp:BoundField DataField="Population" HeaderText="Population" />
                </Columns>
                <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
                <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
                <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
                <RowStyle BackColor="White" ForeColor="#003399" />
                <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
                <SortedAscendingCellStyle BackColor="#EDF6F6" />
                <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
                <SortedDescendingCellStyle BackColor="#D6DFDF" />
                <SortedDescendingHeaderStyle BackColor="#002876" />
            </asp:GridView>
            <br />
            <br />
        </div>
    </div>
    <div align="center">
        <asp:Chart ID="Chart1" runat="server">
            <Series>
                <asp:Series Name="Series1">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                </asp:ChartArea>
            </ChartAreas>
        </asp:Chart>
    </div>
    </form>
</body>
</html>


// Code behind

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

public partial class ChartSample : System.Web.UI.Page
{
    SqlConnection myDataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString);
    string errdesc = "0";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            fillGrid();
            FillChart();
        }
    }

    

    private void fillGrid()
    {
        try
        {
            myDataConnection.Open();

            // Selecting the data from table and binding it to grid.
            
            SqlCommand getdata = new SqlCommand("Select * from Marks", myDataConnection);
            SqlDataAdapter da = new SqlDataAdapter(getdata);
            DataSet ds = new DataSet();
            da.Fill(ds, "Marks");
            xPopulationData.DataSource = ds;
            xPopulationData.DataBind();
            myDataConnection.Close();

        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            


            string Month = TextBox1.Text;

            int Population = Convert.ToInt32(TextBox2.Text);

            myDataConnection.Open();

            // Inserting the values to the table
            SqlCommand comm = new SqlCommand("INSERT INTO Marks(Months,Population) VALUES ('" + Month + "'," + Population + ")", myDataConnection);
            comm.ExecuteNonQuery();
            
            myDataConnection.Close();
            
            litdesc.Text = "Data Saved";
            litdesc.Visible = true;
            fillGrid();
            FillChart();
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
            litdesc.Text = errdesc;
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            myDataConnection.Open();
            int Popfig = Convert.ToInt32(TextBox4.Text);

            // Updating the data to the table.


            SqlCommand getdata = new SqlCommand("update Marks set Population =" + Popfig + " where Months = '" + TextBox3.Text + "'", myDataConnection);
          
            getdata.ExecuteNonQuery();
            myDataConnection.Close();
            litupdate.Visible = true;
            litupdate.Text = "Data Updated";
            fillGrid();
            FillChart();
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            myDataConnection.Open();

            // Over here we search the data and then check what data has come from database.
            SqlCommand getdata = new SqlCommand("Select * from Marks where Months = '" + TextBox3.Text + "'", myDataConnection);
            SqlDataAdapter da = new SqlDataAdapter(getdata);
            DataSet ds = new DataSet();
            da.Fill(ds, "Marks");
            TextBox3.Text = ds.Tables[0].Rows[0]["Months"].ToString();
            TextBox4.Text = ds.Tables[0].Rows[0]["Population"].ToString();
            myDataConnection.Close();
            FillChart();

        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
    }


    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            myDataConnection.Open();

            // Deleting the data after search

            SqlCommand getdata = new SqlCommand("delete from Marks where Months = '" + TextBox3.Text + "'", myDataConnection);
            getdata.ExecuteNonQuery();
            myDataConnection.Close();
            litupdate.Visible = true;
            litupdate.Text = "Data Deleted";
            TextBox3.Text = "";
            TextBox4.Text = "";
            fillGrid();
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
    }


    // This is the main method where the data gets bound to the chart.
    private void FillChart()
    {
        try
        {
            myDataConnection.Open();

            // Get the data from database.

            SqlCommand getdata = new SqlCommand("Select * from Marks", myDataConnection);
            SqlDataAdapter da = new SqlDataAdapter(getdata);
            DataSet ds = new DataSet();
            da.Fill(ds, "Marks");

            // Getting the data into dataset and assigning the dataset as a Datasource to the chart control as Datasource.

            Chart1.DataSource = ds;

            // These are column names of the table these are case sensitive over here you can define the XValue member and Y Value Member

            Chart1.Series["Series1"].XValueMember = "Months"; 
            Chart1.Series["Series1"].YValueMembers = "Population";
            Chart1.DataBind();
        }
        catch (Exception ex)
        {
            errdesc = ex.Message;
        }
    }

}

Different View of the Chart : Line View

 

Note :- You can select what ever view you want you just need to change the chart type as shown in the previous step.



Conclusion


Hope this article helps Programmers in our Beginner level.



Page copy protected against web site content infringement by Copyscape

About the Author

Raj.Trivedi
Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
http://www.dotnetfunda.com/profile/raj.trivedi.aspx
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Posted by: Jayakumars on: 10/9/2013 | Points: 25
Good One Raj how to change chart type using Dropdownlist.

Login to post response

Comment using Facebook(Author doesn't get notification)