Click here to Skip to main content
12,693,891 members (33,386 online)
Click here to Skip to main content
Add your own
alternative version


34 bookmarked

Creating 3DBarChart using ASP.NET 2.0

, 31 Mar 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
How to Create 3DBarChart with Graphics, Bitmap Objects in ASP.NET 2.0


In this article, I will show how to create a 3D BarChart using Drawing objects. This is about creating a 3D Barchart in Web applications. It is often hard to find documentation on these issues, so this article will hopefully allow developers to create their own 3D charts.


The Bitmap image is showing the 3D BarChart by providing X-Axis, Y-Axis co-ordinates with ADO.NET 2.0 functionality and it has Gridview control for showing DataPresentation of the BarChart.

Using the Code

To try out the code, simply download and unzip the files and then start Visual Studio 2005. Choose "Open:Web Site" from the menu and select the directory (3D Bar Chart). I already included a simple Database Path in web.config and it has one DataAccessLayer in App_Code folder with Dal.cs. It contains two *.aspx pages, one is for Bar Chart creation and that will store Imagecontrol in another *.aspx page.

The 3D Bar Chart

It is for showing information in the Graphical Representation of the Purchase amount with their Purchase Order Ids. Simply I haven't taken Bitmap class and Drawing class objects for creating the Rectangular Bar Chart with 3D Effect. By using Bitmap class for canvas for Graph and Graphics class, it has all the functions for drawing the Rectangular, Line etc. Graphics object having Bitmap object for copying the contents of drawing image into Bitmap location. For example:

Bitmap objXValuePanel = new Bitmap(200, 350); 
// Canvas to display x-axis values 
Graphics graphicGraph = Graphics.FromImage(objgraph); 
Graphics graphicXValuePanel = Graphics.FromImage(objXValuePanel);

Values for x, y co-ordinates are taken from the database by providing each having an individual column name in the specific table. E.g.: x—Axis is for POID, y-Axis is for Amount field here. DrawLine is a function for Drawing Lines for X-Axis and Y-Axis and FillRectangle is a function for Drawing Rectangular through from X-Axis and Y-Axis by passing five arguments. Brush---for drawing the lines using solidBrush object with color X-Axis—Position of x-axis Y-Axis----Position of y-axis and X-Axis width, Y-Axis Height E.g.:

graphicGraph.FillRectangle(brush, 200,250, 20, 200); 

Here it has a Gridview ASP.NET 2.0 control for showing DataPresentation of the 3DBar Chart. The gridview id as gvDetails and its autogeneratecolumn is set to true by providing two column information. Binding with Dataset object generated form GetPodetails() function in Dal.cs SqlConnection object for establishing the connection, it is taken from Web.config with ConfigurationManager.ConnectionStrings["ConnectionString"].ToString().

Here is the ConnectionString in Web.config:

  		<add id="sa;password=aqs123;" name=""ConnectionString""
                  providername=""System.Data.SqlClient"" database="3DBarChart""
                  connectionstring=""server=XENO-NEW2;" />  

Now all you have to do is associate the data you want to show in the grid like this:

Dal dal = new Dal(); ---Dal is the class name in App_Code folder for DataAccess
DataSet ds = null;
 private void BindGrid()
            ds = new DataSet();
            ViewState["DsDetails"] = ds;
            gvDetails.DataSource = ds;
        catch (Exception ex)
            throw ex;

Gridview Skin

Now that we have the data, let's make it look a little better. That shouldn't be too hard; the HTML defaults must have been defined by a very good software developer. The GridView can use skins to set its appearance. There are a few predefined skins, from which you can choose by selecting "Auto-Format" in the grid's smart tag. No fun in that, though.

<gridview id="gvDetails"  runat="server" cellpadding="4" forecolor="#333333"
<footerstyle forecolor=""White"" backcolor=""#5D7B9D"" font-bold=""True"" />
<rowstyle forecolor=""#333333"" backcolor=""#F7F6F3"" />
<editrowstyle backcolor=""#999999"" />
<selectedrowstyle forecolor="#333333" backcolor="#E2DED6" font-bold="True" />
<pagerstyle forecolor=""White"" backcolor=""#284775"" horizontalalign=""Center"" />
<headerstyle forecolor="White" backcolor="#5D7B9D" font-bold="True" />
<alternatingrowstyle forecolor=""#284775"" backcolor=""White"" />

Now, here is the code for drawing a 3D BarChart, Chartdisplay.aspx page I called the drawchart() function.

For Generating 3D Bar Chart

public void DrawChart()
       DataSet objds = new DataSet();
       objds = (DataSet)ViewState["DsDetails"];
       Session["dataset"] = objds;
       int count = objds.Tables[0].Rows.Count;
       int result = 0;
       if (objds.Tables[0].Rows.Count > 0)
           string[] keyValue = new string[count];
           float[] values = new float[count];
           for (int i = 0; i < count; i++)
               keyValue[i] = objds.Tables[0].Rows[i]["POLineID"].ToString();
               if (objds.Tables[0].Rows[i]["MerchandiseAmount"].ToString() == null)
                   values[i] = float.Parse("0.0");
                   values[i] = float.Parse(
               if (float.Parse(
                   objds.Tables[0].Rows[i]["MerchandiseAmount"].ToString()) == 0.0)

           if (result != count)
               ImageSelect.Visible = true;
            // the image Control that will have bitmap image after
            // generating 3DBar Chart the Bitmap image
       // will redirect to this image control
               ImageSelect.ImageUrl = FormatURL("PurchaseOrderReport");
               lbl_err.ForeColor = System.Drawing.Color.Red;
               lbl_err.Text = "The image cannot be displayed for zero Amount";
               lbl_err.Visible = true;
               ImageSelect.Visible = false;

For Generating 3D Bar Chart

public string FormatURL(string strArgument)
    return ("Readimage.aspx?report=" + strArgument);

Generating 3DBar Chart is in Readimage.aspx page. It contains the Data Set that is in Session object. It is created in Chartdisplay.aspx page page_load event for Readimage.aspx page:

List<color> colorList;
    protected void Page_Load(object sender, EventArgs e)
        string report=Request.QueryString["report"].ToString();
        DataSet ds = new DataSet();
        DataSet dsevent = new DataSet();
            if (report == "PurchaseOrderReport")
                if (Session["dataset"] != null)
                    ds = (DataSet)Session["dataset"];
            if (ds.Tables[0].Rows.Count > 0)
                int count = ds.Tables[0].Rows.Count;
                string[] keyValue = new string[count];
                float[] values = new float[count];
                for (int i = 0; i < count; i++)
                    keyValue[i] = ds.Tables[0].Rows[i]["POLineID"].ToString();
                    values[i] = float.Parse(

                System.Drawing.Bitmap b3 = new System.Drawing.Bitmap(400, 400);
                b3 = Draw3DBarGraph(keyValue, values);
                Response.ContentType = "image/gif";
                b3.Save(Response.OutputStream, ImageFormat.Gif);
            #region commented
        catch (Exception ex)

Here is the code for generating a 3DBar Chart in Readimage.aspx page. The function returns the Bitmap image after generating a Bar Chart with two array variables like keyValue, Values for X, Y co-ordinates.

public Bitmap Draw3DBarGraph(string[] keyValue, float[] values)
        string xLabel = "POID";
        string yLabel = "MerchandiseAmount";
        string fontFormat = "Courier";
        int alpha = 255;
        Bitmap objgraph = new Bitmap(550, 300);       // Canvas for graph
        Bitmap objXValuePanel = new Bitmap(200, 350); // Canvas to display x-axis values

        Graphics graphicGraph = Graphics.FromImage(objgraph);
        Graphics graphicXValuePanel = Graphics.FromImage(objXValuePanel);

        //    Paint the graph canvas white
        SolidBrush whiteBrush = new SolidBrush(Color.White);
        graphicGraph.FillRectangle(whiteBrush, 0, 0, 550, 300);
        Pen blackPen = new Pen(Color.Black, 2);
        graphicGraph.DrawLine(blackPen, new Point(20, 260), new Point(560, 260));
        graphicGraph.DrawLine(blackPen, new Point(20, 20), new Point(20, 260));
        float highestValue; //Highest value in the values array

        //    Get the highest value 
        float[] tempValue = new float[values.Length];
        for (int j = 0; j < values.Length; j++)
            tempValue[j] = values[j];
        //For calculating the HighestValue in Amount field  and then Fixed the
        //maximum height of the Graph 
        highestValue = tempValue[values.Length - 1];

        //    Generate bar for each value
        for (int i = 0, x = 36; i < values.Length; i++)
            SolidBrush brush = new SolidBrush(Color.FromArgb(alpha, colorList[i]));

            float barHeight;    //height of the bar
            //Calculate the Maximum height for the graph will be divided by
            //the max value in amount field
            barHeight = (values[i] / highestValue) * 170;

            //        Draw continuous shade for 3D effect
            float shadex = x + 10;
            float shadey = 244 - ((int)barHeight) + 10;
            for (int iLoop2 = 0; iLoop2 < 10; iLoop2++)
                graphicGraph.FillRectangle(brush, shadex - iLoop2, shadey - iLoop2,
                    20, barHeight);

            //        Draw bar
            graphicGraph.FillRectangle(new HatchBrush(HatchStyle.Percent50,
                brush.Color), x, 244 - barHeight, 20, barHeight);
            //Draw the X-axis Values 
            graphicGraph.DrawString(keyValue[i].ToString(), new Font("VERDANA",
                float.Parse("10.0"), FontStyle.Regular, GraphicsUnit.Point),
                Brushes.Red, x+5, 260);
            StringFormat sf = new StringFormat(StringFormatFlags.DirectionVertical);
            Font f = new Font(fontFormat, 8);
            SizeF sizef = graphicGraph.MeasureString("<- " + yLabel, f,
                Int32.MaxValue, sf);

            RectangleF rf = new RectangleF(0, 0, sizef.Width, sizef.Height);
            graphicGraph.DrawString((yLabel.Length > 0 ? "<- " : "") + yLabel, f,
                Brushes.Black, rf, sf);
            graphicGraph.DrawString(xLabel + (xLabel.Length > 0 ? " ->" : ""), f,
                Brushes.Black, 30, 285);
            RectangleF rf1 = new RectangleF();
            rf1.X =  x;
            //Value On the Bar in Y Axis 
            rf1.Y = 205-barHeight;
            rf1.Height = barHeight;
            rf1.Width = 50 + x;
            graphicGraph.DrawString(values[i].ToString(), f,Brushes.Red,rf1,sf);
            //        Increment the x position            
            x += 50;

        //    Mask bottom with a white line
        Pen whitePen = new Pen(Color.White, 10);
        graphicGraph.DrawLine(whitePen, new Point(10, 400), new Point(430, 400));

        //    Increase the size of the canvas and draw axis
        //objgraph = EmbedAxis(objgraph, true);

        //    Draw the key-value pair with respective color code
        //objgraph = EmbedXPanel(objgraph);

        return (objgraph);


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Ravikumar Commuri
Web Developer
India India
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionDatabase ? Pin
sozturk_19814-Feb-12 11:00
membersozturk_19814-Feb-12 11:00 
GeneralNice Article. Pin
Thanigainathan.S20-May-09 1:27
memberThanigainathan.S20-May-09 1:27 
GeneralFree Microsoft Chart Controls is for .NET 3.5 Pin
Steve Wellens18-May-09 17:24
memberSteve Wellens18-May-09 17:24 
Generalthis is microsoft chart controls Pin
Savara18-May-09 9:44
memberSavara18-May-09 9:44 
GeneralTry Microsoft free chart controls for ASP Pin
angel.escamilla10-Apr-09 20:10
memberangel.escamilla10-Apr-09 20:10 
GeneralRe: Try Microsoft free chart controls for ASP Pin
Savara18-May-09 9:43
memberSavara18-May-09 9:43 
GeneralPicture says a thousand words Pin
dharam31-Mar-09 6:21
memberdharam31-Mar-09 6:21 
GeneralRe: Picture says a thousand words Pin
Nedim Sabic31-Mar-09 8:34
memberNedim Sabic31-Mar-09 8:34 
GeneralRe: Picture says a thousand words Pin
vodzurk31-Mar-09 23:49
membervodzurk31-Mar-09 23:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170118.1 | Last Updated 1 Apr 2009
Article Copyright 2009 by Ravikumar Commuri
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid