This document is based on Beta2 development
More and more web applications need to use charts to make data display and analysis. For example: voting results show that the company's production statistical display analysis and so on. With the chart to display data, it is intuitive, clear and other advantages.
Traditional ASP technology is not supported, so you have to use Active X or Java Applets to implement this feature. Newly appeared ASP.NET solves this problem, as long as the class displayed in ASP.NET can draw a rich, dynamic chart (Figure 1). This article will tell how to use ASP.NET technology to combine ADO.NET technology to draw bar charts and pie charts.
figure 1
First create a C # class library.
Open vs.net, create a new class library project called Insight_CS.WebCharts, change the name of the solution to Insight, change the Class.cs file name to Insight_CS.WebCharts.cs, and finally open the Insight_CS.WebCharts.cs file. The code is as follows:
/ * Custom class, by entering different parameters, these classes can draw different graphics * /
Using system;
Using system.io; // Used for file access
Using system.data; // Used for data access
Using system.drawing; // Provide basic functions for painting GDI graphics
Using system.drawing.text; // Provide advanced features for painting GDI graphics
Using system.drawing.drawing2d; // Provides painting high-grade 2D, vector graphics
Using system.drawing.imaging; // Provide advanced features for painting GDI graphics
Namespace Insight_CS.WebCharts
{
Public Class Piechart
{
Public pothart ()
{
}
Public void render (String Title, String Subtitle, Int Width, Int Height, Dataset ChartData, Stream Target)
{
const Int Side_length = 400;
Const Int Pie_Diameter = 200;
DataTable DT = chartdata.tables [0];
/ / Take the total base of the pie chart by inputting parameters
FLOAT SUMDATA = 0;
Foreach (DataRow Dr in Dt.ROWS)
{
SUMDATA = Convert.TOSINGLE (DR [1]);
}
// Generate an Image object, and thus generate a Graphics object
Bitmap BM = New Bitmap (Width, Height);
Graphics g = graphics.FromImage (bm);
// Set the properties of the object G
G.scaleTransform ((Convert. Tosingle (Width)) / Side_Length, (Convert. Tosingle (HEIGHT)) / SIDE_LENGTH);
g.smoothingmode = smoothingmode.default;
g.TextRenderingHint = TextRenderingHint.antialias;
// Setting of canvas and side
g.clear (color.white);
g.drawRectangle (Pens.Black, 0, 0, Side_length-1, Side_Length-1);
// Paint pie chart title
G. DrawString (Title, New Font ("Tahoma", 24), Brushes.black, New Pointf (5, 5)); // Paint
G. DrawString (Subtitle, New Font ("Tahoma", 14), Brushes.black, New Pointf (7, 35));
// Paint pie chart
Float curangle = 0;
FLOAT TOTALANGLE = 0;
For (int i = 0; i
{
Curangle = Convert.TOSINGLE (DT.ROWS [I] [1]) / sumdata * 360;
G. Fillpie (New Solidbrush (Chartutil.getChartimemcolor (I)), 100, 65, PIE_DIAMETER, PIE_DIAGETER, TOTALANGLE, CURANGLE;
G. Drawpie (Pens.Black, 100, 65, PIE_DIAMETER, PIE_DIAMETER, TOTALANGLE, CURANGLE);
TOTALANGLE = Curangle;
}
// Painting Graphical Box and Its Text
g.drawRectangle (Pens.Black, 200, 300, 199, 99);
G. DrawString ("Legend", New Font ("Taoma", 12, FontStyle.Bold, Brushes.black, New Pointf (200, 300));
// Painting map
Pointf Boxorigin = New PointF (210, 330);
Pointf textorigin = new pointf (235, 326);
Float percent = 0;
For (int i = 0; i
{
G. FillRectangle (New Solidbrush (Chartutil.getChartimemcolor (i)), Boxorigin.x, Boxorigin.y, 20, 10);
g.drawRectangle (Pens.Black, Boxorigin.x, Boxorigin.y, 20, 10);
Percent = convert.tosingle (dt.rows [i] [1]) / sumdata * 100;
g.drawstring (dt.rows [i] [0] .tostring () "-" DT.ROWS [i] [1] .tostring () "(" Percent.tostring ("0") " %) ", New Font (" Tahoma ", 10), Brushes.black, Textorigin;
Boxorigin.y = 15;
TextORIGIN.Y = 15;
}
// Send the graphic content to the browser via Response.OutputStream
BM.SAVE (Target, Imageformat.gif);
// Recycling resources
bm.dispose ();
g.dispose ();
}
}
// draw a bar chart
Public Class Barchart
{
Public barchart ()
{
}
Public void render (String Title, String Subtitle, Int Width, Int Height, Dataset ChartData, Stream Target)
{
const Int Side_length = 400; Const Int Chart_top = 75;
Const int CHART_HEIGHT = 200;
Const int chart_left = 50;
Const int CHART_WIDTH = 300;
DataTable DT = chartdata.tables [0];
// Calculate the highest point
Float highpoint = 0;
Foreach (DataRow Dr in Dt.ROWS)
{
HightPoint { HIGHPOINT = Convert.TOSINGLE (DR [1]); } } // Create an instance of a Graphics object Bitmap BM = New Bitmap (Width, Height); Graphics g = graphics.FromImage (bm); // Set the bar graphics and text properties G.scaleTransform ((Convert. Tosingle (Width)) / Side_Length, (Convert. Tosingle (HEIGHT)) / SIDE_LENGTH); g.smoothingmode = smoothingmode.default; g.TextRenderingHint = TextRenderingHint.antialias; // Set the canvas and edge g.clear (color.white); g.drawRectangle (Pens.Black, 0, 0, Side_length-1, Side_Length-1); // Draw a big title G. DrawString (Title, New Font ("Tahoma", 24), Brushes.black, New Pointf (5, 5)); // Draw a small title G. DrawString (Subtitle, New Font ("Tahoma", 14), Brushes.black, New Pointf (7, 35)); // draw a bar chart Float barwidth = chart_width / (dt.rows.count * 2); Pointf Barorigin = New Pointf (Chart_left (Barwidth / 2), 0); Float Barheight = Dt.Rows.count; For (int i = 0; i { Barheight = convert.tosingle (dt.rows [i] [1]) * 200 / highpoint; Barorigin.y = chart_top chart_height - barHeight; G. FillRectangle (New Solidbrush (Chartutil.getChartimemcolor (i)), Barorigin.x, Barorigin.y, Barwidth, Barheight; Barorigin.x = Barorigin.x (Barwidth * 2); } // set edge g.drawline (New Pen (Color.Black, 2), New Point (Chart_left, chart_top), New Point (chart_left, chart_top chart_height); g.drawline (New Pen (color.black, 2), new point (chart_left, chart_top chart_height), new point (chart_top chart_height); // Painting Graphical box and text g.drawRectangle (New Pen (Color.Black, 1), 200, 300, 199, 99); G. DrawString ("Legend", New Font ("Taoma", 12, FontStyle.Bold, Brushes.black, New Pointf (200, 300)); // Draw the legend Pointf Boxorigin = New PointF (210, 330); Pointf textorigin = new pointf (235, 326); For (int i = 0; i { G. FillRectangle (New Solidbrush (Chartutil.getChartimemcolor (i)), Boxorigin.x, Boxorigin.y, 20, 10); g.drawRectangle (Pens.Black, Boxorigin.x, Boxorigin.y, 20, 10); g.drawstring (dt.rows [i] [0] .tostring () "-" Dt.Rows [i] [1] .tostring (), New Font ("Taoma", 10), Brushes.black, TextORIGIN); Boxorigin.y = 15; TextORIGIN.Y = 15; } // Output graphics BM.SAVE (Target, Imageformat.gif); //Recycle bm.dispose (); g.dispose (); } } Public Class Chartutil { Public Chartutil () { } Public Static Color getchartitemcolor (int ITEMINDEX) { Color SelectedColor; Switch (itemIndex) { Case 0: SelectedColor = color.blue; Break; Case 1: SELECTEDCOLOR = Color.Red; Break; Case 2: SelectedColor = Color.Yellow; Break; Case 3: SELECTEDCOLOR = color.purple; Break; DEFAULT: SelectedColor = color.green; Break; } Return SELECTEDCOLOR; } } } Code analysis: 1. Introduce some namespace Using system; Using system.io; // Used for file access Using system.data; // Used for data access Using system.drawing; // Provide basic functions for painting GDI graphics Using system.drawing.text; // Provide advanced features for painting GDI graphics Using system.drawing.drawing2d; // Provides painting high-grade 2D, vector graphics Using system.drawing.imaging; // Provide advanced features for painting GDI graphics These Namespace will be applied later. 2. Customize a namespace for INSIGHT_CS.WEBCHARTS, including two classes of PieChart and Barchart, very clear, Class Piechart is built for painting charts, Class Barchart is built for drawing bar. Because Class Piechart and Class Barchar are almost, so we take the pie chart as an example for code analysis. 3. Class PIECHART establishes a method Render, which can contain some parameters. Briefly illustrate as follows: Parameter title, representation of the big title text above the pie chart. Parameters Subtitle, indicating the small title text above the pie chart. Parameters width, Height, indicating the size of the entire graph. Parameter Chardata is a DataSet object instance for drawing it. The parameter Target is an instance of the Stream object and is used for graphics output. 4. In order to increase readability, define some constants: Const int side_length = 400; // canvas const Int Pie_Diameter = 200; // Pie Diameter 5. Define a DataTable, which is a data table in the DataSet. Among them, the various data of the pie chart is stored. 6. By calculation, draw the total base sumdata in the pie chart. 7. Create a BitMap object that provides memory space for graphics to be created. And thus generate a Graphics object, which encapsulates the GDI draw interface. 8. Call the method of the Graphics object ScaleTransform (), which is used to set the graphical ratio. 9. Call Method SmoothingMode (), TextRenderingHint (), etc. to set the relevant properties of text and graphics. 9. Set the canvas and edges. 10. Set the text title, legend, painting pie, itself. 11. Via stream, send the contents of the graph to the browser. 12. Last recycling resources. The class of this painting pie chart is completed. The method of painting a bar chart and the method of painting the pie chart are similar, and it will not be disclosed here. Overall, it is difficult to build a picture of the drawing without what we think, and there is not a deep algorithm. In fact, the overall idea is as if we use a pen to draw a paper on paper. The key is the use and parameter settings of each method. We have completed the custom class of the pie chart and bar chart in front, and we will apply these classes. Use VS.Net to create a web application called Insight_CS and add it to the INSIGHT project. Delete the default WebForm1.aspx file, create a newly called Saleschart.aspx file. Open this file, replace the first row in code mode: <% @ Page ContentType = "image / gif" Language = "c #" autoeventwireup = "false" codebehind = "saleschart.aspx.cs" inherits = "Insight_cs.saleschart"%>%>%>%> Open the file Saleschart.aspx.cs, where the code is as follows: Using system; Using system.data; Using system.Web; Using system.io; Using system.data.sqlclient; Using Insight_cs.webcharts; // This is a custom name space Namespace Insight_CS { Public class saleschart: system.web.ui.page { Public Saleschart () { Page.init = New System.EventHandler (Page_init); } Private Void Page_Load (Object Sender, System.EventArgs E) { // Take data from the database for drawing String SQL = "SELECT" "Year (sa.ord_date) AS [Year]," "SUM (SA.QTY) AS [Qty] " from " " Sales SA " " Inner Join Store St ON ( Sa.stor_id = st.stor_id) " " GROUP BY " " Year (sa.ord_date) " " Order by " " [Year] " String connectstring = "password = BEN; user ID = sa; database = public = localhost"; SqlDataAdapter Da = New SqlDataAdapter (SQL, ConnectString); DataSet DS = New DataSet (); Int rows = da.fill (DS, "chartdata"); / / Set the type of generated map (PIE or BAR) String Type = ""; IF (null == request ["type"]) { TYPE = "PIE"; } Else { TYPE = Request ["Type"]. TOSTRING (). TouPper (); } // Set the picture size INT width = 0; IF (null == request ["width"]) { Width = 400; } Else { Width = Convert.Toint32 (Request ["Width"]); } INT height = 0; IF (null == request ["height"]) { HEIGHT = 400; } Else { HEIGHT = Convert.Toint32 (Request ["Height"]); } // Set the chart title String Title = ""; IF (NULL! = Request ["Title"]) { Title = Request ["title"]. Tostring (); } String subtitle = "" IF (null! = request ["subtitle"]) { Subtitle = Request ["subtitle"]. TOSTRING (); } IF (0 { Switch (Type) { Case "PIE": PieChart PC = New Piechart (); Pc.render (Title, Subtitle, Width, Height, DS, Response.outputStream); Break; Case "bar": BARCHART BC = New Barchart (); Bc.render (Title, Subtitle, Width, Height, DS, Response.outputStream); Break; DEFAULT: Break; } } } Private void Page_init (Object Sender, Eventargs E) { // // Codegen: This Call is Required by The ASP.NET Web Form Designer. // InitializationComponent (); } #Region Web Form Designer Generated Code /// /// Required Method for Designer Support - Do Not Modify /// The contents of this method with the code editor. /// summary> Private vidinitiRizeComponent () { This.Load = New System.EventHandler (this.page_load); } #ndregion } } The above code is not difficult, and it is not analyzed here. In VS.NET, open Insight_CS Solution, right-click "Reference", add "Add Reference", add component file INSIGHT_CS.WEBCHARTS.DLL to make it a Namespace in the project. Below we can browse the results. First build a demochart.aspx file, in its code, add the content:
SRC = "SalesChart.aspx? type = piers& width = 300 & height = 30 0 & Title = Sales By Year & Subtitle = Books>
SRC = "Saleschart.aspx? type = bar & width = 300 & height = 30 0 & Title = Sales By Year & Subtitle = Books> TYPE indicates the type of display graphics, is the pie chart PIE, or a bar chart bar. Width, Height represents the size of the graph. Title represents a big headline text. Subtitle represents a small title text. The result is shown in Figure 1 (picture in article "ASP.NET drawing full Raiders (on)"). Thus, we have completed the process of drawing using the ASP.NET technology.