ASP.NET 4.0 introduced inbuilt chart controls features. This Chart control has several types like Line, Column, Pie etc. In this post I am going to talk about how you can change the ASP.NET Chart Control Type on the fly. . All the Chart Type for ASP.NET 4.0 Chart control are defined in a public enum SeriesChartType. We will be using dynamic Enum Binding with DropDownList Control to get all the list of types
So first bind the SeriesChartType enum value in dropdown. You can read one of my post on Generic Way to Bind Enum With Different ASP.NET List Controls .
First Write the Generic method to get the enum and control type.
public void BindEnumToListControls(Type enumType, ListControl listcontrol) { string[] names = Enum.GetNames(enumType); listcontrol.DataSource = names.Select((key, value) => new { key, value }).ToDictionary(x => x.key, x => x.value + 1); listcontrol.DataTextField = "Key"; listcontrol.DataValueField = "Value"; listcontrol.DataBind(); }
Call the methods from Page_Load() to bind the records
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindEnumToListControls(typeof(SeriesChartType), ddlCharType); } }
This will populate and bind all types of Chart Control in the dropdown list.
Once You are done, On DropDown SelectionIndex_Change, you can change the type of chart control. Before that placed a chart control and bind the data on that
protected void ddlCharType_SelectedIndexChanged(object sender, EventArgs e) { this.Chart1.Series["Series1"].ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), ddlCharType.SelectedItem.Text); }
Well, that’s all, you can change the dropdown list value and get reflect of changed chart control type .