Categories
Asp, Asp.net

Bar Chart Control Example With Database In Asp.Net

Bar Chart Control Example With Database In Asp.Net

In this tutorial i will explain how to useĀ Bar Chart Control Example With Database In Asp.Net.We are using SQL Server as backend, on that we have a table with column Student_Names and Student_Marks.In this example we are showing these records in a bar chart.

Design:

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How To Use Bar Chart Control In Asp.Net</title>
<style type="text/css">
body
{
margin:0px auto;
width:980px;
font-family:Calibri;
font-size:14px;
}
.bar 
{
text-align:center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="text-align:center">How To Use Bar Chart Control In Asp.Net</h2>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:BarChart ID="BarChart1" ChartType="Bar" CssClass="bar" runat="server"></asp:BarChart>
</div>
</form>
</body>
</html>

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


public partial class Index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection("Data Source=.;User ID=sa;Password=sa;Initial Catalog=testing");
        conn.Open();
       
        SqlCommand cmd = new SqlCommand("select s_name,s_marks from marks", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        string[] x = new string[dt.Rows.Count];
        decimal[] y = new decimal[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            x[i] = dt.Rows[i][0].ToString();
            y[i] = Convert.ToInt32(dt.Rows[i][1]);
        }
        BarChart1.Series.Add(new AjaxControlToolkit.BarChartSeries { Data = y });
        BarChart1.CategoriesAxis = string.Join(",", x);

        BarChart1.ChartWidth = (x.Length * 160).ToString();
        BarChart1.ChartHeight = (y.Length * 50).ToString();
        
        
        
    }
}