Click here to Skip to main content
15,884,803 members
Articles / Web Development / ASP.NET

ASP.NET AJAX MultiHandleSliderExtender - Slide by Year and Month

Rate me:
Please Sign up or sign in to vote.
4.68/5 (14 votes)
20 Apr 2010CPOL8 min read 63.3K   2.1K   36  
Tutorial - How to utilize the ASP.NET MultiHandleSlider extender to select year and month in a range, and set the Chart controls in action.
  • multihandlesliderextender_w_chart_v1.zip
    • MultiHandleSliderExtender_w_Chart
      • mssccprj.scc
      • MultiHandleSliderExtender_w_Chart.sln
      • MultiHandleSliderExtender_w_Chart.vssscc
      • MultiHandleSliderExtender_w_Chart
        • App_Code
        • App_Data
        • Bin
          • AjaxControlToolkit.dll
          • ar
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • cs
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • de
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • es
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • fr
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • he
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • hi
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • it
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • ja
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • ko
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • nl
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • pt
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • ru
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • System.Web.DataVisualization.Design.dll
          • System.Web.DataVisualization.dll
          • tr-TR
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • vssver2.scc
          • zh-CHS
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
          • zh-CHT
            • AjaxControlToolkit.resources.dll
            • vssver2.scc
        • ChartPic_000003.png
        • Default.aspx
        • Default.aspx.cs
        • Default2.aspx
        • MasterPage.master
        • MasterPage.master.cs
        • Readme.txt
        • vssver2.scc
        • web.config
      • vssver2.scc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Xml.Linq;
using System.Collections;
using System.Drawing;
using System.Web.UI.DataVisualization.Charting;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
    protected static List<Range> lstSliderRange = null;
    Random rand = new Random();

    protected void Page_Load(object sender, EventArgs e)
    {
        Chart1.Click += new ImageMapEventHandler(Chart1_Click);

        PopulateSlider();

        if (!Page.IsPostBack)
        {
            //slider min and max value
            MultiHandleSliderExtender1.Minimum = 1;
            MultiHandleSliderExtender1.Maximum = int.Parse(lstSliderRange.Max(r => r.RowNumber).ToString());

            //hidden field
            rangeEnd.Value = MultiHandleSliderExtender1.Maximum.ToString();
            rangeStart.Value = MultiHandleSliderExtender1.Minimum.ToString();

            CreateArray();

            PopulateChart(int.Parse(rangeStart.Value), int.Parse(rangeEnd.Value));      
        }

        SetLabel();
    }

    void CreateArray()
    {
        foreach (Range r in lstSliderRange)
        {
            Page.ClientScript.RegisterArrayDeclaration("arrRange", "'"+r.Year +"--" + r.Month+"'");
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        PopulateGrid(ChartPostBackValue.Value);
    }

    void PopulateChart(int start, int end)
    {
        List<CarsList> lstCarsnTotal = new List<CarsList>();

        XDocument xmlDoc = XDocument.Load(Server.MapPath(Utilities.Instance.CarsListXMLPath));
        lstCarsnTotal = (from c in xmlDoc.Descendants("Car")
                         where (int)c.Attribute("YearMonth") >= GetRange(start) && (int)c.Attribute("YearMonth") <= GetRange(end)
                         group c by (string)c.Attribute("CarBrand") into g

                         select new CarsList
                         {
                             CarCount = g.Sum(c => (int)c.Attribute("Count")),
                             CarBrand = g.Key
                         }).ToList();

        #region chartRegion
        this.Chart1.Series[0].PostBackValue = "#AXISLABEL";

        Chart1.Series["Default"].SmartLabelStyle.Enabled = false;
        Chart1.Series["Default"].LabelAngle = -45;

        Chart1.Series["Default"].ChartType = SeriesChartType.Column;
        Chart1.Series["Default"].Points.DataBindXY(lstCarsnTotal, "CarBrand", lstCarsnTotal, "CarCount");

        Chart1.Series["Default"].IsXValueIndexed = true;
        Chart1.Series["Default"].IsVisibleInLegend = false;

        Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;

        Chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Angle = -45;

        Chart1.Series["Default"].IsValueShownAsLabel = true;
        Chart1.Series["Default"]["DrawingStyle"] = "Cylinder";

        Chart1.Series["Default"]["ShowMarkerLines"] = "true";
        Chart1.Series["Default"]["PointWidth"] = "0.9";

        // Set series visual attributes
        Chart1.Series["Default"].BackSecondaryColor = Color.Green;
        Chart1.Series["Default"].BackGradientStyle = GradientStyle.DiagonalLeft;

        Chart1.Series["Default"].BorderColor = Color.Black;
        Chart1.Series["Default"].BorderWidth = 2;
        Chart1.Series["Default"].BorderDashStyle = ChartDashStyle.Solid;

        Chart1.Series["Default"].ShadowOffset = 2;

        //remove HTML tags
        Chart1.Titles[0].Text = System.Text.RegularExpressions.Regex.Replace(
                    String.Format("Cars on Sesame Street {0} {1}", GetSliderText(start.ToString(), "s"),
                            GetSliderText(end.ToString(), "e")), @"<(.|\n)*?>", string.Empty);

        // Set Antialiasing mode
        Chart1.AntiAliasing = AntiAliasingStyles.All;
        Chart1.TextAntiAliasingQuality = TextAntiAliasingQuality.High;

        //set random colors
        for (int pointIndex = 0; pointIndex < Chart1.Series["Default"].Points.Count; pointIndex++)
        {
            Chart1.Series["Default"].Points[pointIndex].Color = GetRandomColor();
        }

        Chart1.Focus();
        #endregion
    }

    protected void Chart1_Click(object sender, ImageMapEventArgs e)
    {
        if (!GridView1.Visible)
        {
            GridView1.Visible = true;
        }
        //kept track of selected car type
        ChartPostBackValue.Value = e.PostBackValue;
        lblCarBrand.Text = "Car Brand: " + e.PostBackValue;

        PopulateGrid(e.PostBackValue);
        PopulateChart(int.Parse(rangeStart.Value), int.Parse(rangeEnd.Value));
    }

    void PopulateGrid(string strPostBavkVal)
    {
        List<CarsList> lstCarsnTotal = new List<CarsList>();

        XDocument xmlDoc = XDocument.Load(Server.MapPath(Utilities.Instance.CarsListXMLPath));
        lstCarsnTotal = (from c in xmlDoc.Descendants("Car")
                         where (int)c.Attribute("YearMonth") >= GetRange(int.Parse(rangeStart.Value))
                         && (int)c.Attribute("YearMonth") <= GetRange(int.Parse(rangeEnd.Value)) && (string)c.Attribute("CarBrand") == strPostBavkVal
                         select new CarsList
                         {
                             CarCount = (int)c.Attribute("Count"),
                             CarBrand = (string)c.Attribute("CarBrand"),
                             Date = (string)c.Attribute("Date")
                         }).ToList();

        GridView1.DataSource = lstCarsnTotal;
        GridView1.DataBind();
    }

    public Color GetRandomColor()
    {
        return Color.FromArgb(rand.Next(0, 256), rand.Next(0, 256), rand.Next(0, 256));
    }

    //set the slider start and end label
    void SetLabel()
    {
        string[] arrLabel = SliderRange(rangeStart.Value, rangeEnd.Value).Split("--".ToCharArray());
        lblStartRange.Text = arrLabel[0];
        lblEndRange.Text = arrLabel[2];
    }

    //get slider range
    void PopulateSlider()
    {
        //Cache the frequently used data
        if (Cache["Cache_lstSliderRange"] == null)
        {
            XDocument xmlDoc = XDocument.Load(Server.MapPath(Utilities.Instance.SliderRangeXMLPath));
            lstSliderRange = (from c in xmlDoc.Descendants("Range")
                              select new Range
                              {
                                  Month = (string)c.Attribute("Month"),
                                  Year = (string)c.Attribute("Year"),
                                  RowNumber = (int)c.Attribute("RowNumber")
                              }).ToList();

            Cache.Insert("Cache_lstSliderRange", lstSliderRange,
                new System.Web.Caching.CacheDependency(Server.MapPath(Utilities.Instance.SliderRangeXMLPath)));
        }
        else
        {
            lstSliderRange = Cache["Cache_lstSliderRange"] as List<Range>;
        }
    }

    [System.Web.Services.WebMethod]
    public static string SliderRange(string start, string end)
    {
        if (lstSliderRange != null)
        {
            return GetSliderText(start, "s") + "--" + GetSliderText(end, "e");
        }
        else
        {
            return "";
        }
    }

    //return YearMonth
    protected static int GetRange(int rn)
    {
        IEnumerable<Range> rangeText;

        rangeText = lstSliderRange.Where(r => r.RowNumber == rn)
            .Select(r => new Range
            {
                Year = r.Year,
                Month = r.Month
            });

        return int.Parse(rangeText.First().Year + rangeText.First().Month);
    }

    protected static string GetSliderText(string rn, string pos)
    {
        string strRangeText = string.Empty;
        IEnumerable<Range> rangeText;

        rangeText = lstSliderRange.Where(r => r.RowNumber == int.Parse(rn))
            .Select(r => new Range
            {
                Year = r.Year,
                Month = r.Month
            });

        if (pos == "s")
        {
            strRangeText = "<b>From</b> Year: " + rangeText.First().Year + " Month: " + rangeText.First().Month;
            return strRangeText;
        }
        else
        {
            strRangeText = "<b>To</b> Year: " + rangeText.First().Year + " Month: " + rangeText.First().Month;
            return strRangeText;
        }
    }

    protected void btnLoadChart_Click(object sender, EventArgs e)
    {
        // hide the gridview
        GridView1.Visible = false;
        //keep track of the range
        hdfTrackRangeStart.Value = rangeStart.Value;
        hdfTrackRangeEnd.Value = rangeEnd.Value;
        lblCarBrand.Text = String.Empty;
        UpdatePanel1.Update();
        PopulateChart(int.Parse(rangeStart.Value), int.Parse(rangeEnd.Value));
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
I have over 10 years of experience working with Microsoft technologies. I have earned my Microsoft Certified Technology Specialist (MCTS) certification. I'm a highly motivated self-starter with an aptitude for learning new skills quickly.

Comments and Discussions