ASPAlliance.com : The #1 Active Server Pages .NET Community The #1 ASP.NET Community
Search   Search

Subscribe   Subscribe

Powered by ORCSWeb Hosting


Site Stats


Powered By ASP.NET
 
Featured Sponsor

Featured Columnist


Featured Book
ASP.NET Unleashed
ASP.NET Unleashed

Find Prices
Read Review
Sample Chapter
Sample Chapter
Sample Chapter
Sample Chapter


New! asp.netPRO

We publish our articles in the standard RSS format.

Powerful .NET Email Component

Code Sharing Software
Jeff's Home Page
Jeff's Articles

Dynamically Create Bar and Pie Charts in ASP.NET (Step-by-Step)

Author: Jeff Nuckolls
(April 2002)

Creating dynamically generated graphs and charts to graphically represent data from some data source in any application has often been a major requirement for developers.  In most cases developers would have to resort to sometimes costly third-part component to accomplish these tasks.  However, the new GDI+ classes and objects available in the Microsoft .NET Framework make it easy to create custom images and graphics on-the-fly, including leveraging information from any data source.  In this article, I will walk through some simple steps of creating bar chart and pie chart images in ASP.NET based on information from a data source. (For the purpose of this article I will use an array, but you can easily modify this code to pull information from a database.)

 

Note:

This sample application was created and tested in Visual Studio .NET (RTM).

Download the source code for this article.

 

 

Step 1 – Create a new ASP.NET project

  1. Click START à PROGRAMS à MICROSOFT VIUSAL STUDIO .NET à NEW PROJECT
  2. The New Project dialog box shown in Figure 1 will appear.
  3. Select VISUAL BASIC from the Project Types pane on the left and then ASP.NET Web Application from the Templates pane on the right.
  4. Change the name of the application from WebApplication1 to ASPCharts.
  5. Click OK

Figure 1:

This will automatically create a web project called ASPCharts under the wwwroot directory.

 

Step 2 – Add some HTML to the default page (WebForm1.aspx)

This page will have some HTML image tags that will act as containers for our graphs that we will create in Step 3.

  1. Switch to the HTML view of the WebForm.aspx page.
  2. Add the following HTML between the <FORM> tags.

<table width="100%" height="100%">

      <tr>

            <td align="middle">

                  <img src="Charts.aspx">

            </td>

      </tr>

</table>

Notice in the <img> tag points to the Charts.aspx Web Form page as the source for an image path.  The Charts.aspx page returns a binary GIF object via the Response object's OutputStream.  The Charts.aspx does not return any text only a binary GIF object. (NOTE: You could also return a JPEG or BMP object as well.)

 

Step 3 – Add a new Web Form page named (Charts.aspx)

  1. From the Solution Explorer window right click on the ASPCharts project.
  2. Click ADD à ADD NEW ITEM
  3. The Web Add New Item dialog box will appear, select Web Form from the Templates pane on the right.
  4. Change the name from WebForm2.aspx to Charts.aspx.
  5. Click Open

 

Step 4 – Add code to the Charts.aspx Web Form page

Now comes the fun part of programmatically and dynamically generating a bar graph and returning it as an image source to the WebForm1.aspx page.

  1. Right click the Charts.aspx Web Form and click View Code from the menu options to view the Code Behind page.
  2. Add the following code as described below.

Before we can use the Drawing objects of the GDI+ classes, we must first reference the namespace that contain these objects at the top of our code page as follows:

Imports System.Drawing

Imports System.Drawing.Imaging

Now we will add the code that will create our bar and pie graph image in the Page_Load event as follows:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    'Declare your object variables

    Dim i As Integer

 

    'Build a BitMap that will act as the pallet and container

    'for the bar graph. Here 600 is the width and 300 is the height. 

    'These values could also be passed as parameters.

    Dim objBitMap As New Bitmap(400, 200)

 

    'Declare your Graphics objects for painting graphics on you newly created bitmap.

    Dim objGraphics As Graphics

    objGraphics = Graphics.FromImage(objBitMap)

    'Set the background color to silver

    objGraphics.Clear(Color.Silver)

 

    'Build an array of values for the bar and pie chart. 

    'These values could also be pulled from a database.

    Dim arrValues(4) As Integer

    arrValues(0) = 100

    arrValues(1) = 135

    arrValues(2) = 115

    arrValues(3) = 125

    arrValues(4) = 75

 

    Dim arrValueNames(4) As String

    arrValueNames(0) = "Jan"

    arrValueNames(1) = "Feb"

    arrValueNames(2) = "Mar"

    arrValueNames(3) = "Apr"

    arrValueNames(4) = "May"

 

    'Write out a title for your bar and pie chart.

    objGraphics.DrawString("5 Month Projection Report", New Font("Tahoma", 16), Brushes.Black, New PointF(5, 5))

 

    'Create a legend to describe your bar and chart.

    Dim symbolLeg As PointF = New PointF(335, 20)

    Dim descLeg As PointF = New PointF(360, 16)

 

    For i = 0 To arrValueNames.Length - 1

        objGraphics.FillRectangle(New SolidBrush(GetColor(i)), symbolLeg.X, symbolLeg.Y, 20, 10)

        objGraphics.DrawRectangle(Pens.Black, symbolLeg.X, symbolLeg.Y, 20, 10)

 

        objGraphics.DrawString(arrValueNames(i).ToString, New Font("Tahoma", 10), Brushes.Black, descLeg)

        symbolLeg.Y += 15

        descLeg.Y += 15

    Next i

 

    'Loop through the values to create the Bar Chart.

    For i = 0 To arrValues.Length - 1

        objGraphics.FillRectangle(New SolidBrush(GetColor(i)), (i * 35) + 15, 200 - arrValues(i), 20, arrValues(i) + 5)

        objGraphics.DrawRectangle(Pens.Black, (i * 35) + 15, 200 - arrValues(i), 20, arrValues(i) + 5)

    Next

 

    'Loop through the values to create the Pie Chart.

    Dim sglCurrentAngle As Single = 0

    Dim sglTotalAngle As Single = 0

    i = 0

 

    For i = 0 To arrValues.Length - 1

        'Current Value / (sum of all the Values) * 360 degree angle

        sglCurrentAngle = arrValues(i) / 550 * 360

 

        objGraphics.FillPie(New SolidBrush(GetColor(i)), 220, 95, 100, 100, sglTotalAngle, sglCurrentAngle)

        objGraphics.DrawPie(Pens.Black, 220, 95, 100, 100, sglTotalAngle, sglCurrentAngle)

 

        sglTotalAngle += sglCurrentAngle

    Next i

 

    objBitMap.Save(Response.OutputStream, ImageFormat.Gif)

 

End Sub

The following function is called from the Page_Load event to return different colors for each value contained in our bar and pie charts.

'This function returns a color for the bar and pie charts.

Private Function GetColor(ByVal itemIndex As Integer) As Color

    Dim objColor As Color

 

    Select Case itemIndex

        Case 0

            objColor = Color.Blue

        Case 1

            objColor = Color.Red

        Case 2

            objColor = Color.Yellow

        Case 3

            objColor = Color.Purple

        Case 4

            objColor = Color.Orange

        Case 5

            objColor = Color.Brown

        Case 6

            objColor = Color.Gray

        Case 7

            objColor = Color.Maroon

        Case Else

            objColor = Color.Green

    End Select

 

    Return objColor

 

End Function

 

Step 5 – Save and Run

  1. From the menu bar click FILE à SAVE ALL
  2. Click F5 to Debug and Run your application.

If you didn’t receive any errors you should see something simular to Figure 2.

Figure 2:

In this sample application we show you how easy it is to leverage the GDI+ classes and objects; however, we have only skimmed the surface here.  I would strongly encourage looking into some of the more advanced features available in the System.Drawing.Drawing2D namespace.  You might also want to extend this sample to include pulling data from a database instead of using an array of values.

 

Author’s Bio:

Jeff Nuckolls (MCSE, MCSD, MCP+I, ASE) is an industry leading Software Architect with a background in Software, Network, and System Engineering.  Specializing in Microsoft .NET Development tools and technologies, he actively contributes to technical articles, whitepapers, and user groups while also speaking at several conferences and formal training events. Jeff can be reached at jeffnuck@microsoft.com.

 Copyright © 2000-2003 ASPAlliance.com  Page Rendered at 11/21/2009 7:00:09 PM