2015年10月14日 星期三

Google Chart APIs: Google (Pie / Doughnut) Chart example with database in ASP.Net

In this article I will explain how to use Google Chart APIs with database in ASP.Net using C#, VB.Net and jQuery.
In this example I will populate Pie chart, 3D Pie chart and Doughnut chart from database using jQuery AJAX and WebMethods in ASP.Net.
 
Database
For this article I am making use of the Microsoft’s Northwind Database. Download and install instructions are provided in the link below
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Data
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
 
 
WebMethod
The following WebMethod will be used for populating the Pie chart, 3D Pie chart and Doughnut chart from database.
The SQL Query gets the City-wise Order distribution for the country United States. The results are populated into a two dimensional object array using DataReader, which is finally sent to client as a Generic List of objects.
C#
[WebMethod]
public static List<object> GetChartData()
{
    string query = "SELECT ShipCity, COUNT(orderid) TotalOrders";
    query += " FROM Orders WHERE ShipCountry = 'USA' GROUP BY ShipCity";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    List<object> chartData = new List<object>();
    chartData.Add(new object[]
    {
        "ShipCity""TotalOrders"
    });
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    chartData.Add(new object[]
                    {
                        sdr["ShipCity"], sdr["TotalOrders"]
                    });
                }
            }
            con.Close();
            return chartData;
        }
    }
}
 
VB.Net
<WebMethod()> _
Public Shared Function GetChartData() As List(Of Object)
    Dim query As String = "SELECT ShipCity, COUNT(orderid) TotalOrders"
    query += " FROM Orders WHERE ShipCountry = 'USA' GROUP BY ShipCity"
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim chartData As New List(Of Object)()
    chartData.Add(New Object() {"ShipCity""TotalOrders"})
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    chartData.Add(New Object() {sdr("ShipCity"), sdr("TotalOrders")})
                End While
            End Using
            con.Close()
            Return chartData
        End Using
    End Using
End Function
 
 
Populate Google Charts from database in ASP.Net using jQuery AJAX
The concept is simple i.e. to get the chart data from the database with the use of WebMethod (described earlier) and jQuery AJAX and then use the data for chart population.
 
Pie Chart
The very first thing is to load the Google Chart API packages and when once all the packages are loaded then the drawChart method is invoked.
Inside this method a jQuery AJAX call to the WebMethod is initiated which gets the records from the database as an array of objects.
The array of objects are converted to a Google Visualization DataTable and used for drawing the chart on to the specified HTML DIV element.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization""1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
    var options = {
        title: 'USA City Distribution'
    };
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetChartData",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var data = google.visualization.arrayToDataTable(r.d);
            var chart = new google.visualization.PieChart($("#chart")[0]);
            chart.draw(data, options);
        },
        failure: function (r) {
            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
    });
}
</script>
<div id="chart" style="width: 900px; height: 500px;">
</div>
 
Google Chart APIs: Google (Pie / Doughnut) Chart example with database in ASP.Net
 
3D Pie Chart
The 3D Pie chart is actually a Pie chart with a 3-dimensional look and feel. The population part is very similar to the Pie chart and we just need to set an additional property is3D to true.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization""1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
    var options = {
        title: 'USA City Distribution',
        is3D: true
    };
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetChartData",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var data = google.visualization.arrayToDataTable(r.d);
            var chart = new google.visualization.PieChart($("#chart")[0]);
            chart.draw(data, options);
        },
        failure: function (r) {
            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
    });
}
</script>
<div id="chart" style="width: 900px; height: 500px;">
</div>
 
Google Chart APIs: Google (Pie / Doughnut) Chart example with database in ASP.Net
 
Doughnut Chart
The final chart is a Doughnut chart which again is similar to a Pie chart but has a hole at the center resembling a Doughnut. The population part is very similar to the Pie chart and we just need to set an additional property pieHole to the size of the hole we need.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization""1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
    var options = {
        title: 'USA City Distribution',
        pieHole: 0.5
    };
    $.ajax({
        type: "POST",
        url: "Default.aspx/GetChartData",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            var data = google.visualization.arrayToDataTable(r.d);
            var chart = new google.visualization.PieChart($("#chart")[0]);
            chart.draw(data, options);
        },
        failure: function (r) {
            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
    });
}
</script>
<div id="chart" style="width: 900px; height: 500px;">
</div>
 
Google Chart APIs: Google (Pie / Doughnut) Chart example with database in ASP.Net
 
Demo
 
Downloads

2015年10月11日 星期日

Implement jQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net

In this article I will explain how to implement and populate jQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net using C# and VB.Net.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.
 
 
HTML Markup
The following HTML Markup of Page consists of an ASP.Net TextBox, a HiddenField and a Button.
The jQuery AutoComplete plugin has been applied to the TextBox. A jQuery AJAX call is made to the GetCustomers PageMethod and the list of customers returned from the PageMethod acts as source of data to the jQuery AutoComplete.
The data received from the server is processed in the jQuery AJAX call success event handler. A loop is executed for each received item in the list of items and then an object with text part in the label property and value part in the val property is returned.
A Select event handler has been defined for the jQuery AutoComplete and when an item is selected from the AutoComplete List, the value of the item is stored in the HiddenField.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css"
    rel="Stylesheet" type="text/css" />
<script type="text/javascript">
    $(function () {
        $("[id$=txtSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=hfCustomerId]").val(i.item.val);
            },
            minLength: 1
        });
    });  
</script>
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />
 
 
Namespaces
You will need to import the following namespaces.
C#
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient
 
 
 The ASP.Net PageMethod
The following AJAX PageMethod accepts a parameter prefix and its value is used to find matching records from the Customers Table of the Northwind database.
The select query gets the Name and the ID of the customer that matches the prefix text.
The fetched records are processed and a Key Value Pair is created by appending the Id to the Name field in the following format {0}-{1} where is the Name {0} and {1} is the ID of the Customer.
 C#
[WebMethod]
public static string[] GetCustomers(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select ContactName, CustomerId from Customers where ContactName like @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
                }
            }
            conn.Close();
        }
    }
    return customers.ToArray();
}
 
VB.Net
<WebMethod()>
Public Shared Function GetCustomers(prefix As StringAs String()
    Dim customers As New List(Of String)()
    Using conn As New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As New SqlCommand()
            cmd.CommandText = "select ContactName, CustomerId from Customers where ContactName like @SearchText + '%'"
            cmd.Parameters.AddWithValue("@SearchText", prefix)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    customers.Add(String.Format("{0}-{1}", sdr("ContactName"), sdr("CustomerId")))
                End While
            End Using
            conn.Close()
        End Using
    End Using
    Return customers.ToArray()
End Function
 
 
Fetching the selected item on Server Side
The Key (Customer Name) and Value (Customer ID) can be fetched on server side inside the click event handler of the Button from the Request.Form collection as shown below.
 C#
protected void Submit(object sender, EventArgs e)
{
    string customerName = Request.Form[txtSearch.UniqueID];
    string customerId = Request.Form[hfCustomerId.UniqueID];
    ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('Name: " + customerName + "\\nID: " + customerId + "');"true);
}
 
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
    Dim customerName As String = Request.Form(txtSearch.UniqueID)
    Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
    ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('Name: " & customerName & "\nID: " & customerId & "');"True)
End Sub
 
 
Screenshot
Implement jQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net
 
 
Demo
 
 
Downloads