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);
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;
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); Bitmap objXValuePanel = new Bitmap(200, 350);
Graphics graphicGraph = Graphics.FromImage(objgraph);
Graphics graphicXValuePanel = Graphics.FromImage(objXValuePanel);
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;
float[] tempValue = new float[values.Length];
for (int j = 0; j < values.Length; j++)
{
tempValue[j] = values[j];
}
Array.Sort<float>(tempValue);
highestValue = tempValue[values.Length - 1];
for (int i = 0, x = 36; i < values.Length; i++)
{
SolidBrush brush = new SolidBrush(Color.FromArgb(alpha, colorList[i]));
float barHeight; barHeight = (values[i] / highestValue) * 170;
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);
}
graphicGraph.FillRectangle(new HatchBrush(HatchStyle.Percent50,
brush.Color), x, 244 - barHeight, 20, barHeight);
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;
rf1.Y = 205-barHeight;
rf1.Height = barHeight;
rf1.Width = 50 + x;
graphicGraph.DrawString(values[i].ToString(), f,Brushes.Red,rf1,sf);
x += 50;
}
Pen whitePen = new Pen(Color.White, 10);
graphicGraph.DrawLine(whitePen, new Point(10, 400), new Point(430, 400));
return (objgraph);
}