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

Creating 3DBarChart using ASP.NET 2.0

0.00/5 (No votes)
31 Mar 2009 1  
How to Create 3DBarChart with Graphics, Bitmap Objects in ASP.NET 2.0

Introduction

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.

Background

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:

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

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()
    {
        try
        {
            ds = new DataSet();
            ds=dal.GetPodetails();
            ViewState["DsDetails"] = ds;
            gvDetails.DataSource = ds;
            gvDetails.DataBind();
        }
        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"
    gridlines="None"> 
<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"" />
</gridview>

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");
                else
                    values[i] = float.Parse(
                        objds.Tables[0].Rows[i]["POLineID"].ToString());
                if (float.Parse(
                    objds.Tables[0].Rows[i]["MerchandiseAmount"].ToString()) == 0.0)
                {
                    result++;
                }                
            }         
         
            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");
            }
            else
            {
                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();
      
        try
        {
            if (report == "PurchaseOrderReport")
            {
                if (Session["dataset"] != null)
                    ds = (DataSet)Session["dataset"];
                InitColorList();
               
            }
            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(
                        ds.Tables[0].Rows[i]["MerchandiseAmount"].ToString());

                }
                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
          
            #endregion
        }
        catch (Exception ex)
        {
            ex.ToString();
        }
    }

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];
        }
        Array.Sort<float>(tempValue);
        //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);
    }

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