使用 ASP.NET CHART CONTROL、c# 添加动态图表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/335061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:40:27  来源:igfitidea点击:

Add dynamic charts using ASP.NET CHART CONTROL, c#

c#asp.net

提问by

I wanted to add dynamic charts in the webpage. It goes like this...

我想在网页中添加动态图表。它是这样的......

I get the start and end date from user and draw separate charts for each date bewteen the start and end date.

我从用户那里获取开始和结束日期,并为开始和结束日期之间的每个日期绘制单独的图表。

I get the data from sql database and bind it with the chart like this:

我从 sql 数据库中获取数据并将其与图表绑定,如下所示:

   SqlConnection UsageLogConn = new   
          SqlConnection(ConfigurationManager.ConnectionStrings["UsageConn"].ConnectionString);
                UsageLogConn.Open();//open connection

                string sql = "SELECT v.interval,dateadd(mi,(v.interval-1)*2,'" + startdate + " 00:00:00') as 'intervaltime',COUNT(Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2) AS Total  FROM usage_internet_intervals v left outer join (select * from Usage_Internet where " + name + "  LIKE ('%" + value + "%') and DateTime BETWEEN '" + startdate + " 00:00:00' AND '" + enddate + " 23:59:59') d on v.interval = Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 GROUP BY v.interval,Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 ORDER BY Interval";

                SqlCommand cmd = new SqlCommand(sql, UsageLogConn);
                SqlDataAdapter mySQLadapter = new SqlDataAdapter(cmd);

                Chart1.DataSource = cmd;

                // set series members names for the X and Y values 
                Chart1.Series["Series 1"].XValueMember = "intervaltime";
                Chart1.Series["Series 1"].YValueMembers = "Total";
                UsageLogConn.Close();
                // data bind to the selected data source
                Chart1.DataBind();


                cmd.Dispose();

The above code adds only one chart for one date and I have added 'chart1' to design view and its not created dynamic. But I wanted to add more charts dynamic at runtime to the webpage.

上面的代码只为一个日期添加了一个图表,我在设计视图中添加了“chart1”,它不是动态创建的。但我想在运行时向网页添加更多动态图表。

Can anyone help me with this?

谁能帮我这个?

I am using VS 2008, ASP.NET 3.5 and the charting lib is: using System.Web.UI.DataVisualization.Charting;

我使用的是 VS 2008、ASP.NET 3.5,图表库是: using System.Web.UI.DataVisualization.Charting;

回答by Programmin Tool

Ok so I may have overdone this, but I tried to make this pretty dynamic. Yeah, the list names are a bit odd, but I used another example of mine to build this.

好吧,我可能做得过火了,但我试图让它变得非常有活力。是的,列表名称有点奇怪,但我使用了我的另一个示例来构建它。

 protected void Page_Load(object sender, EventArgs e)
 {
   Bench[] benchList;
   FoodIntake[] foodIntakeList;
   Panel panelChartHolder;

   panelChartHolder = new Panel();
   Controls.Add(panelChartHolder);

   benchList = Bench.GetAll();
   AddNewCharts(benchList, panelChartHolder, 
     GetBenchXValue, GetBenchYValue);

   foodIntakeList = FoodIntake.GetAll();
   AddNewCharts(foodIntakeList, panelChartHolder, 
     GetFoodIntakeXValue, GetFoodIntakeYValue);
  }

Ok so this first part is simple. Create a panel to hold the charts you are adding, get the lists you want represented by the charts (For this example they happen to work with Linq to Sql) and call the method to create the charts.

好的,所以这第一部分很简单。创建一个面板来保存您正在添加的图表,获取您想要由图表表示的列表(在本示例中,它们碰巧与 Linq to Sql 一起使用)并调用该方法来创建图表。

  private void AddNewCharts<T>(T[] listToAdd, Panel panelToAddTo, 
     Func<T, DateTime> xMethod, Func<T, Int32> yMethod)
  {

    ChartArea mainArea;
    Chart mainChart;
    Series mainSeries;

    mainChart = new Chart();
    mainSeries = new Series("MainSeries");

    for (Int32 loopCounter = 0; loopCounter < listToAdd.Length; loopCounter++)
    {
      mainSeries.Points.AddXY(xMethod(listToAdd[loopCounter]), 
        yMethod(listToAdd[loopCounter]));
    }

    mainChart.Series.Add(mainSeries);
    mainArea = new ChartArea("MainArea");
    mainChart.ChartAreas.Add(mainArea);

    panelToAddTo.Controls.Add(mainChart);
  }

As you can see, I just created a new chart, added a series to it, and added a ChartArea to it. Next part is pretty much just looping through the collection and adding each item in it to the list itself. It uses the passed in delegate methods (Func) to get the X and Y values.

如您所见,我刚刚创建了一个新图表,向其中添加了一个系列,并在其中添加了一个 ChartArea。下一部分几乎只是遍历集合并将其中的每个项目添加到列表本身。它使用传入的委托方法 (Func) 来获取 X 和 Y 值。

Last part holds the four methods responsible for getting the X and Y values from the two lists. Basically I did this to allow the chart creating method to be a generic as possible. Might be overkill.

最后一部分包含负责从两个列表中获取 X 和 Y 值的四种方法。基本上我这样做是为了让图表创建方法尽可能通用。可能是矫枉过正了。

  private DateTime GetBenchXValue(Bench currentBench)
  {
    return currentBench.DateLifted;
  }

  private Int32 GetBenchYValue(Bench currentBench)
  {
    return currentBench.BenchAmount;
  }

  private DateTime GetFoodIntakeXValue(FoodIntake currentIntake)
  {
    return currentIntake.DateEaten;
  }

  private Int32 GetFoodIntakeYValue(FoodIntake currentIntake)
  {
    return currentIntake.Calories;
  }

And so when you run this, you will get two graphs side by side. Mind you, they will be very plain as there are million different properties that can be set to improve the look. Hope this is what you were asking for.

所以当你运行这个时,你会得到两个并排的图。请注意,它们将非常简单,因为可以设置数百万种不同的属性来改善外观。希望这是你所要求的。

  using System;
  using System.Web.UI.DataVisualization.Charting;
  using System.Web.UI.WebControls;

回答by Dave Haynes

I have updated the MS chart samples for .NET 4.0 and added two additional projects -- ChartsWithMVC and ChartsWithoutWebForms. You might find my sample code helpful, as I have a very basic implementation of a dynamic chart system using the asp.net chart control:

我已经更新了 .NET 4.0 的 MS 图表示例,并添加了两个额外的项目——ChartsWithMVC 和 ChartsWithoutWebForms。您可能会发现我的示例代码很有帮助,因为我有一个使用 asp.net 图表控件的动态图表系统的非常基本的实现:

http://develocity.blogspot.com/2010/04/aspnet-chart-controls-without-web-forms.html

http://develocity.blogspot.com/2010/04/aspnet-chart-controls-without-web-forms.html

Hope it helps.

希望能帮助到你。

回答by shridhar

protected void Page_Load(object sender, EventArgs e)
    {
        MySqlConnection UsageLogConn = new MySqlConnection("Server=localhost;UID=root;Password=;database=productactivation");
        UsageLogConn.Open();//open connection

        string sql = "select * from sales";
        DataSet ds = new DataSet();
        MySqlCommand cmd = new MySqlCommand(sql, UsageLogConn);
        MySqlDataAdapter mySQLadapter = new MySqlDataAdapter(cmd);
        mySQLadapter.Fill(ds);
        Chart1.DataSource = ds;

        // set series members names for the X and Y values 
        Chart1.Series["Series1"].XValueMember = "title_id";
        Chart1.Series["Series1"].YValueMembers = "qty";
        Chart1.Series["Series2"].XValueMember = "title_id";
        Chart1.Series["Series2"].YValueMembers = "qty";
        UsageLogConn.Close();
        // data bind to the selected data source
        Chart1.DataBind();


        cmd.Dispose();

    }