Chart type selection from Dropdown and Adding new Series from Code behind

Today we will give our chart control a new power, power of being able to add new series from code behind as well as including letting our users choose the chart type of new series from dropdown list.

So to get started lets place our aspx markup for chart and dropdown list control as follows:

<asp:DropDownList ID="DropDownList1" runat="server"

onselectedindexchanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">

<asp:ListItem Selected="True">Select</asp:ListItem>

<asp:ListItem Value="Line">Line Chart</asp:ListItem>

<asp:ListItem Value="Area">Area Chart</asp:ListItem>



<asp:Chart ID="Chart1" runat="server">


<asp:Series Name="Series1">




<asp:ChartArea Name="ChartArea1">





In the code above, under dropdown list we are defining two chart types Line and Area, from which user can choose what kind of chart they want to see.

Here is what code behind file will look like:

private static int counter = 1;

protected void Page_Load(object sender, EventArgs e)


// Collection to hold X Axis and Y Axis Values

Dictionary<string,int> xyValue=new Dictionary<string,int>();


// Call to chart Data method which return dictionary collection of demo data

xyValue= chartData();


// Binding collection key value pair to chart's default series

Chart1.Series[0].Points.DataBindXY(xyValue.Keys, xyValue.Values);



public Dictionary<string,int> chartData()


// Object to generate random numbers to populate demo data

Random rnd = new Random(1);


Dictionary<string, int> values = new Dictionary<string, int>();


//Populating collection with random values

for (int i = 0; i < 10; i++)


values.Add("Value " + i, rnd.Next(200));


return values;



protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)


if (!DropDownList1.SelectedValue.Equals("Select"))


Dictionary<string,int> xyValue=new Dictionary<string,int>();

xyValue= chartData();


// Creating new series with counter

// so name will be unique when we add this series to chart series collection

Series newSeries = new Series("newSeries" + counter);



// Here we are using Enum.Parse to parse string from dropdown to     

     // SeriesChartType enumeration type

newSeries.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), DropDownList1.SelectedValue.ToString());


newSeries.Points.DataBindXY(xyValue.Keys, xyValue.Values);


// Assigning chart area of new series to same as chart area of default series

newSeries.ChartArea = Chart1.Series[0].ChartArea;


// Adding chart to chart1's series collection





Important this to note here is by using Enum.Parse we are able to cast string value, which is returned from dropdown list, to enumeration of chart type.

Now if we run our page and select area from dropdown list, our page will look something like this:

Tags: , ,

ASP.NET | MS Chart