Skip to main content

Dynamic charts with ASP.NET, Windows chart controls


We all know how important charting is now days. We all store lots of data but the end users generally are the people who do not have much time to use it after putting in hours in correlating and analyzing it. They generally ask for reports charts etc. Traditionally either we had to use GDI+ or buy a third party tool to provide these facilities. MS has started providing this facility free of cost since 2008 (though it was not part of 3.5 framework but one can download the exe and can install it). Starting from framework 4.0 charting controls are also shipping with .NET.
It is quite easy to use chart controls, let us see how.
Create a web application project and from the toolbox (in design mode) drag chart control. It will be present under the data section.
aspdotnetcharting1
Configure the datasource and set the chart type and X and Y column for the chart.
aspdotnetcharting2
I am using a SQLDataSource and AdventureWorks as my DB.
Now we are good to go. Press F5 and you can see the chart.
Let us extend the functionality a bit
Drop three drop downs and a button on you page. First drop down is for selecting the chart type and other two are for selecting the X and Y columns.
This will provide the end user with flexibility to select different X and Y parameters and different chart types.
aspdotnetcharting3
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Charting
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                populateXandY();
                Array obj = Enum.GetValues(typeof(System.Web.UI.DataVisualization.Charting.SeriesChartType));
                foreach (System.Web.UI.DataVisualization.Charting.SeriesChartType types in obj)
                {
                    ddChartType.Items.Add(new ListItem(types.ToString()));
                }
               
            }
        }
        protected void btnChart_Click(object sender, EventArgs e)
        {
            MyChart.Series[0].XValueMember = X.SelectedValue;
            MyChart.Series[0].XValueMember = Y.SelectedValue;
           
            MyChart.Series[0].ChartType = (System.Web.UI.DataVisualization.Charting.SeriesChartType)Enum.Parse(typeof(System.Web.UI.DataVisualization.Charting.SeriesChartType), ddChartType.SelectedValue, true);
        }
        private void populateXandY()
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AdventureWorksLT2008ConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand("SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'SalesOrderDetail'", con);
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                X.Items.Add(new ListItem(dr[0].ToString(),dr[0].ToString()));
                Y.Items.Add(new ListItem(dr[0].ToString(), dr[0].ToString()));
            }
            con.Close();
        }
    }
}

Explanation
I have just queried the concerned table using information schema to find out the columns and listed the columns in the dropdowns X and Y. You can be smarter and can list only the needed columns Smile.
Then I have listed all the available chart types (from System.Web.UI.DataVisualization.Charting.SeriesChartType  enum) in ddChartType dropdown.
Button is used to postback and set the chart type and X and Y column value for the chart control.

Check out this book for advanced topics.



Comments

Popular posts from this blog

Create a background / taskbar application in c# .NET

Recently, I was working on integration of two windows applications. First application will launch the second application on login and then they both will communicate using pre-defined set of instructions. There were some complications (I am not going into them) and thus we decided to have a third application which actually will act as mediator. First application will launch the mediator (third application) and it will launch the second application. For this purpose we needed to create a task bar application (which will run in background). How To ·          Create a new windows project and delete the default form (Form1). ·          In Program.cs create a new class and inherit it from Form. ·          Please refer the code below. ·          Now change the Main method. In Application.Run change the startup objec...

Check SQL Server Job status (State) using sp_help_job and xp_sqlagent_enum_jobs

This article is about checking the status of a SQL job. In our work place we have lot of SQL jobs. These jobs will run whole day and are business critical. They will load the data and generate extracts which will be used by business people. Thus, it becomes quite essential to support the system efficiently so that the job finishes in time and as desired. Also, while designing a new system sometimes we need to check the dependency of one job over another. In such scenario we need to check whether a particular job has finished or not. All this can be achieved in SQL Server by using the procedures:- sp_help_job xp_sqlagent_enum_jobs Note: xp_sqlagent_enum_jobs is an undocumented proc inside of sp_help_job and is used extensively to get SQL agent job information. sp_help_job: This procedure gives some insight into the status, and information, about a job. This stored procedure provides information such as last start time, job status etc. Syntax sp_help_job { [ @job_id= ] jo...

Java 8 JMX Default Metrics

This is more of a note. Here you can find default types and attributes for JMX on top of Java 8. Code: I will clean and explain it later :( private static void WriteAttributes(final MBeanServer mBeanServer, final ObjectName http) throws InstanceNotFoundException, IntrospectionException, ReflectionException { MBeanInfo info = mBeanServer.getMBeanInfo(http); MBeanAttributeInfo[] attrInfo = info.getAttributes(); System.out.println("Attributes for object: " + http +":\n"); for (MBeanAttributeInfo attr : attrInfo) { System.out.println(" " + attr.getName() + "\n"); } } Attributes for object: java.lang:type=MemoryPool,name=Metaspace:   Name   Type   Valid   Usage   PeakUsage   MemoryManagerNames   UsageThreshold   UsageThresholdExceeded   UsageThresholdCount   UsageThresholdSupported   CollectionUsageThreshold   Collectio...