5
votes

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:

   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.

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;

3

3 Answers

4
votes

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.

  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.

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.

  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;
2
votes
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();

    }
0
votes

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:

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

Hope it helps.