Saturday 4 May 2013

Asp.net 4.0 Bind Chart to XML

.aspx.cs

using System;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

       protected void btnBindChart_Click(object sender, EventArgs e)
    {
        string dataPath = MapPath(".") + "\\books.xml";

        DataSet ds = new DataSet();
        ds.ReadXml(dataPath);
        DataTable dt = ds.Tables[0];
        DataView dataView = new DataView(dt);
        // Bind XML
        chartBooks.Series[0].Points.DataBindXY(dataView, "title", dataView, "price");       
    }
}

.aspx:

<%@ Page Title="Home Page" Language="C#"  AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

    <asp:Button ID="btnBindChart" runat="server" Text="Bind Chart to XML"
        onclick="btnBindChart_Click" />
    <asp:Chart ID="chartBooks" runat="server"  Width="700" Height="450"
         BackColor="LightBlue" BackSecondaryColor="AliceBlue"
         BackGradientStyle="TopBottom" BorderColor="DarkBlue">
        <Series>
            <asp:Series Name="Series1" ChartArea="ChartArea1" ChartType="Column"
                Color="Wheat">
            </asp:Series>
        </Series>
        <ChartAreas>
            <asp:ChartArea Name="ChartArea1" Area3DStyle-Enable3D="true" 
            BackColor="#0066cc" BorderColor="DarkBlue">
            </asp:ChartArea>
        </ChartAreas>
    </asp:Chart>