日期:2014-03-16  浏览次数:20474 次

我们在前面已经完成了饼图和条形图的自定义类,下面我们将要应用这些类了。
  使用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.