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
- Understanding the Chart Control.
- Binding data to the Chart Control.
Using the code
- Open Visual Studio -> Create a New Empty Web site.
- Add 1 Web form as SampleChart in the page.
- Now Drag and drop total 4 Textboxes, 4 buttons, 2 Literal.
- Now drag and drop a Grid and a Chart control from the Toolbox under the data toolbox.
- Your UI Should be like in the Screen Shot.
Screen
Explanation of the Chart Control.
- The Chart Control has 2 important properties i.e. Series and Chart Area.
- Series allows you to define the X and Y axis member to display the chart.
- The X Value member is the range and Y value member is the actual value for the range.
- In this article we are visualizing the strength of population year wise
- So the X member will Year and the Y value member will be the value.
- The chart area is the area that will display the chart as per the data coming from the database.
Explanation of the Application.
- In this application we will first enter month and the value of the population.
- Once we enter the data in the database the data will bind it to the grid.
- The same data will be bounded to the Chart Control and show it in the Bar Diagram.
- We can also change the view of the chart by changing the Chart Type.
- Chart Type can be changed by clicking the arrow on top corner of the Chart Control.Check the screen.
- 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">
</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">
</td>
<td class="style5">
Enter Month
</td>
<td class="style6" colspan="2">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
</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">
</td>
<td class="style5">
Change Population Figure
</td>
<td class="style6">
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</td>
<td class="style11">
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style12">
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
</td>
<td class="style10">
</td>
<td class="style5">
</td>
<td class="style6" colspan="2">
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
</td>
</tr>
<tr>
<td class="style3">
</td>
<td class="style12">
<asp:Literal ID="litdesc" Visible="false" runat="server"></asp:Literal>
</td>
<td class="style10">
</td>
<td class="style5">
</td>
<td class="style6">
<asp:Literal ID="litupdate" Visible="false" runat="server"></asp:Literal>
</td>
<td class="style11">
</td>
</tr>
</table>
<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.