65.9K
CodeProject is changing. Read more.
Home

Visual Data using Chart.js in ASP.NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (6 votes)

Sep 6, 2018

CPOL
viewsIcon

52642

Using Chart.js to visual data from MS SQL Server database on ASP.NET web form

Introduction

The best way to introduce some information to some is using chart. ASP.NET has a chart control but it is 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 downloaded in the previous step to root project
  3. Create a 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 writing 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 details 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 a better way than the table.