Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Visual data using Chart.js in ASP.NET

0.00/5 (No votes)
5 Sep 2018 1  
Using Chart.js to visual data from MS SQL Server database on ASP.NET web form

Introduction

The best way to introlduce some information to some is using chart. ASP.NET have a chart control but it not the best about performance. Chart.js is a good ideal.

Background

- Working with MS SQL Database

- Javascript

- Web form

Using the code

1. Download Chart.js

You can get Chart.js from this addess:  https://github.com/chartjs/Chart.js/releases

2. Create new ASP.NET project with Visual Studio and copy Chart.js was download in previous step to root project

3. Create new Web form with name "Home.aspx" and add some code lines like this

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="VisualData.Home" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="ChartJS.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Literal ID="ltChart" runat="server"></asp:Literal>
    </div>
    </form>
</body>
</html>

4. Open Web.config file to add new connection string to connect to your MS SQL Server database

<configuration>
    <system.web>
      <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <connectionStrings>
    <add name="myConnection" connectionString="Data Source=.\mySQLInstance; initial catalog=myDatabaseName; user id=myUsername; password=myPassword;"/>
  </connectionStrings>
</configuration>

5. Switch to code view and start write some code

private void ShowData()
        {
            String myConnection = ConfigurationManager.ConnectionStrings["myConnection"].ToString();
            SqlConnection con = new SqlConnection(myConnection);
            String query = "Select top 100 AirTemperature From tbWeathers Where stationID=1 order by id desc";
            SqlCommand cmd = new SqlCommand(query, con);
            DataTable tb = new DataTable();
            try
            {
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                tb.Load(dr, LoadOption.OverwriteChanges);
                con.Close();
            }
            catch { }

            if(tb != null)
            {
                String chart = "";
               // You can change your chart height by modify height value
                chart = "<canvas id=\"line-chart\" width=\"100%\" height=\"40\"></canvas>";
                chart += "<script>";
                chart += "new Chart(document.getElementById(\"line-chart\"), { type: 'line', data: {labels: [";

                // more detais in x-axis
                for (int i = 0; i < 100; i++)
                    chart += i.ToString() + ",";
                chart = chart.Substring(0, chart.Length - 1);

                chart += "],datasets: [{ data: [";
                
                // put data from database to chart
                String value = "";
                for (int i = 0; i < tb.Rows.Count; i++)
                    value += tb.Rows[i]["NhietDo"].ToString() + ",";
                value = value.Substring(0, value.Length - 1);

                chart += value;

                chart += "],label: \"Air Temperature\",borderColor: \"#3e95cd\",fill: true}"; // Chart color
                chart += "]},options: { title: { display: true,text: 'Air Temperature (oC)'} }"; // Chart title
                chart += "});";
                chart += "</script>";

                ltChart.Text = chart;
            }            
        }

6. Build project and run to show your result

Points of Interest

Now you can display your data in the better way than the table.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here