我們在前面已經完成了餅圖和條形圖的自定義類,下面我們將要應用這些類了。
使用vs.net新建一個名為Insight_cs的Web應用程序,並且添加到剛才的Insight工程中。刪除默認的webform1.aspx文件,新建一個名為SalesChart.aspx文件。
打開此文件,在代碼模式下,將第一行替換為:
<%@ Page ContentType="image/gif" Language="c#" AutoEventWireup="false" Codebehind="SalesChart.aspx.cs" Inherits="Insight_cs.SalesChart" %> 打開文件SalesChart.aspx.cs,其中代碼如下所示: using System; using System.Data; using System.Web; using System.IO; using System.Data.SqlClient; using Insight_cs.WebCharts;//這是自定義的名字空間 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) { //從數據庫中取得數據,用於畫圖 string sql = "SELECT " +"Year(sa.ord_date) As [Year], " +"SUM(sa.qty) As [Qty] " +"FROM " +"sales sa " +"inner join stores 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=pubs;Data Source=localhost"; SqlDataAdapter da = new SqlDataAdapter(sql,connectString); DataSet ds = new DataSet(); int rows = da.Fill(ds,"chartData"); //設定產生圖的類型(pie or bar) string type = ""; if(null==Request["type"]) { type = "PIE"; } else { type = Request["type"].ToString().ToUpper(); } //設置圖大小 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"]); } //設置圖表標題 string title = ""; if(null!=Request["title"]) { title = Request["title"].ToString(); } string subTitle = ""; if(null!=Request["subtitle"]) { subTitle = Request["subtitle"].ToString(); } if(0<rows) { 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. // InitializeComponent(); } #region Web Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion } }
以上的代碼並沒有什麼難的,這裡就不做分析了。