c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
.Net

How to bind data from database to chart control in asp.net?

| | ASP-NET , chart , webconfig

In this article we will discuss, to bind data from database to chart control in asp.net. To connect the database by using connection string, retrieve data from database and binding to chart control .

Step 1: create a drowpdownlist and bind chart type name on it and set AutoPostBack to true. We can change chart type as our wish.

Step 2: Create a table using the following script with data:

USE [ShoppingZone]
GO
/****** Object:  Table[dbo].[Visitors]    Script Date:05/03/2016 17:16:31 ******/
SET ANSI_NULLSON
GO
SET QUOTED_IDENTIFIERON
GO
CREATE TABLE[dbo].[Visitors](
      [Id] [int] IDENTITY(1,1) NOT NULL,
      [Day] [nvarchar](50) NOT NULL,
      [VisitorCount] [int] NOT NULL,
 CONSTRAINT[PK_Visitors] PRIMARY KEYCLUSTERED
(
      [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]
GO
SET IDENTITY_INSERT[dbo].[Visitors] ON
INSERT [dbo].[Visitors] ([Id], [Day],[VisitorCount]) VALUES(1, N'sun', 800)
INSERT [dbo].[Visitors] ([Id], [Day],[VisitorCount]) VALUES(2, N'mon', 900)
INSERT [dbo].[Visitors] ([Id], [Day],[VisitorCount]) VALUES(4, N'tue', 700)
INSERT [dbo].[Visitors] ([Id], [Day],[VisitorCount]) VALUES(5, N'wed', 900)
INSERT [dbo].[Visitors] ([Id], [Day],[VisitorCount]) VALUES(6, N'thu', 600)
INSERT [dbo].[Visitors] ([Id], [Day],[VisitorCount]) VALUES(7, N'fri', 750)
INSERT [dbo].[Visitors] ([Id], [Day],[VisitorCount]) VALUES(8, N'sat', 950)
SET IDENTITY_INSERT [dbo].[Visitors] OFF

Step 3: Copy and paste the following code.

Flowchart.aspx: 

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Flowchart.aspx.cs" Inherits="_Default" %>
 <%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
     <table style="border: 1px solid #e2e2e2; font-family: Arial">
        <tr>
            <td>
                <b>Select Chart Type:</b>
            </td>
            <td>
                <asp:DropDownList ID="ChartType" AutoPostBack="true" runat="server"
                   OnSelectedIndexChanged="ChartType_SelectedIndexChanged">
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Chart ID="Chart1" runat="server" Width="450px">
                   <Titles>
                       <asp:Title Text="website visitors">
                       </asp:Title>
                   </Titles>
                   <Series>
                       <asp:Series Name="Series1" ChartArea="ChartArea1" ChartType="point">
                       </asp:Series>
                   </Series>
                   <ChartAreas>
                       <asp:ChartArea Name="ChartArea1">
                            <AxisX Title="week">
                            </AxisX>
                            <AxisY Title="visitors per day">
                            </AxisY>
                       </asp:ChartArea>
                   </ChartAreas>
                </asp:Chart>
            </td>
        </tr>
    </table>
</asp:Content>

Flowchart.aspx.cs:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls; 

public partial class _Flowchart : Page
{
        protected void Page_Load(object sender, EventArgs e)

        {
            if (!IsPostBack)
            {
               GetChartTypes();
                GetChartData();
            }
        }

       private void GetChartData()
       
{

           string cs = ConfigurationManager.ConnectionStrings["ShoppingZone"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
           // Command to retrieve Students data from Students table
               SqlCommand cmd = new
               SqlCommand("Select Day, VisitorCount from Visitors", con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                // Retrieve the Series to which we want to add DataPoints
                Series series = Chart1.Series["Series1"];
                // Loop thru each Student record
                while (rdr.Read())
                {
                   // Add X and Y values using AddXY() method
                   series.Points.AddXY(rdr["Day"].ToString(),
                        rdr["VisitorCount"]);
                }
            }
        }
        private void GetChartTypes()
        {
            foreach (int chartType in Enum.GetValues(typeof(SeriesChartType)))
            {
                ListItem li = new ListItem(Enum.GetName(typeof(SeriesChartType),
                    chartType), chartType.ToString());
                ChartType.Items.Add(li);
            }
        }

      protected void ChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
GetChartData();
            this.Chart1.Series["Series1"].ChartType = (SeriesChartType)Enum.Parse(
                typeof(SeriesChartType), ChartType.SelectedValue);
        }
    }

 

Output: