Chart a Course With ASP.NET Graphics
Build Web graphics on the fly using the .NET Framework classes.
by Jonathan Goodyear, MCSD, MCP, CLS
M any Web applications that facilitate data analysis require support for charts and other graphics. After all, a picture is worth a thousand words. Traditional ASP did not support these capabilities, so you had to rely on third-party components or Java applets to get the job done. With ASP.NET, you can leverage the graphics classes in the .NET Framework, opening the door for you to create rich, dynamic charts. This article will show you how to build a pie chart and a bar chart, based on an ADO.NET DataSet object (see Figure 1).
NOTE: The source code discussed in this article is C#, but a VB.NET version is also available for download. All code for this article was developed using Beta 2 of the .NET Framework and Visual Studio .NET.
First, you need to build a charting library. Fire up Visual Studio .NET and create a new Visual C# Class Library project. Name the project Insight_cs.WebCharts. Name the solution that is created "Insight." Finally, rename Class1.cs to Insight_cs.WebCharts.cs, and open it up (see Listing 1).
The first few lines of code import the namespaces containing the classes your charting library will use. Create the namespace Insight_cs.WebCharts, so you can reference your charting library from your ASP.NET project (which we'll build a bit later). Note that the VB.NET version of the code does not require the namespace to be included in the source code. Instead, it is specified through the Root namespace parameter of the VB.NET class project. Create a PieChart class. Nothing is required to initialize the class so it has an empty constructor.
The PieChart class has a single method, Render, which accepts several parameters. The title parameter will appear at the top of our chart. The subTitle parameter will appear just below the title. The width and height parameters determine how large (in pixels) the chart image will be. The chartData parameter is a reference to a DataSet object containing the data that will be used to render your pie chart. Lastly, the target parameter is a reference to a Stream object. In the case of an ASP.NET project, you will pass in the OutputStream property of the Response object for this parameter.
After defining some constants to help make the code more readable, get a reference to the first DataTable instance in the DataSet that was passed in as the chartData parameter. Calculate the total number of units that will be used to render the pie sections in the chart accurately. Next, create a new instance of a BitMap object, specifying its width and height in its constructor. You can get a reference to a Graphics object by making a call to the static FromImage method of the Graphics class, passing in your new BitMap object. You will make many calls to this Graphics object to draw the elements of your pie chart.
Back to top
|