在asp.net中动态添加图表控件

时间:2012-07-26 03:51:33

标签: asp.net

我需要在运行时动态添加图表。实际上是多个图表。例如:我必须从数据库中获取14周的记录并显示每周图表中的记录。(即14个图表) 。但周数可能因用户和图表而异。 那么,我该如何克服这个问题?

我很感激有关此事的任何想法。

Chart Chart1 = new Chart();

          Chart1.Series.Add(new Series());


          Chart1.ChartAreas.Add(new ChartArea());
          Chart1.ChartAreas[0].Area3DStyle.Enable3D = false;

           Chart1.Series[0].YValueMembers = "Value";
           Chart1.Series.Add(new Series());
           Chart1.Series[1].YValueMembers = "AnotherValue";
           Chart1.DataSource = lsttest;
           Chart1.DataBind();

           Chart1.Series[0].Color = Color.Blue;
           Chart1.Series[1].Color = Color.DarkGreen;

           Chart1.ChartAreas["ChartArea1"].AxisY.Title = "Count";
           Chart1.ChartAreas["ChartArea1"].AxisX.Title = "Status";
           Chart1.Series[0].IsValueShownAsLabel = true;
           Chart1.Series[1].IsValueShownAsLabel = true;

        Chart1.ImageType = System.Web.UI.DataVisualization.Charting.ChartImageType.Jpeg;

        Chart1.Width = new System.Web.UI.WebControls.Unit(300, System.Web.UI.WebControls.UnitType.Pixel);
        Chart1.Height = new System.Web.UI.WebControls.Unit(200, System.Web.UI.WebControls.UnitType.Pixel);

2 个答案:

答案 0 :(得分:2)

您的代码是正确的,您需要做的就是将其置于一个循环中并使其在您想要的任意次数上运行。在创建新图表时,请使用循环计数器。

所以在这一行之后添加循环:

Chart Chart1 = new Chart();
for(int i=1;i<=n;i++)
{
     Chart1.ID="Chart "+i;
}

答案 1 :(得分:0)

使用PlaceHolder并将图表控件附加到它。

for(int i=1;i<=n;i++)
{
     Chart1.ID="Chart "+i;
     Chart chart1 = new Chart();
     createChart(dt.Tables[0],chart1); // function to create charts
     chartPlaceHolder.Controls.Add(chart1);
}


private void createChart(DataTable dt, Chart chart1)
{
          Chart1.Series.Add(new Series());

          Chart1.ChartAreas.Add(new ChartArea());
          Chart1.ChartAreas[0].Area3DStyle.Enable3D = false;

           Chart1.Series[0].YValueMembers = "Value";
           Chart1.Series.Add(new Series());
           Chart1.Series[1].YValueMembers = "AnotherValue";
           Chart1.DataSource = dt;
           Chart1.DataBind();

           Chart1.Series[0].Color = Color.Blue;
           Chart1.Series[1].Color = Color.DarkGreen;

           Chart1.ChartAreas["ChartArea1"].AxisY.Title = "Count";
           Chart1.ChartAreas["ChartArea1"].AxisX.Title = "Status";
           Chart1.Series[0].IsValueShownAsLabel = true;
           Chart1.Series[1].IsValueShownAsLabel = true;

    Chart1.ImageType = System.Web.UI.DataVisualization.Charting.ChartImageType.Jpeg;
    
    Chart1.Width = new System.Web.UI.WebControls.Unit(300, System.Web.UI.WebControls.UnitType.Pixel);
    Chart1.Height = new System.Web.UI.WebControls.Unit(200, System.Web.UI.WebControls.UnitType.Pixel);

}