Binding XML file to ASP.NET Chart Control

Step 1 : Add an XML file to the project. Name it Employee.xml


<?xml version="1.0" encoding="utf-8" ?>
<Employees>
  <Employee>
    <ID>1</ID>
    <EmployeeName>Srinath</EmployeeName>
    <Salary>50000</Salary>
  </Employee>
  <Employee>
    <ID>2</ID>
    <EmployeeName>Naveen</EmployeeName>
    <Salary>60000</Salary>
  </Employee>
  <Employee>
    <ID>3</ID>
    <EmployeeName>Krishna</EmployeeName>
    <Salary>70000</Salary>
  </Employee>
 

</Employees>


Step 2: Drag and drop chart control on to the webform1.aspx the html code look like this

<asp:Chart ID="Chart1" runat="server">
            <series>
                <asp:Series Name="Series1">
                </asp:Series>
            </series>
            <chartareas>
                <asp:ChartArea Name="ChartArea1">
                </asp:ChartArea>
            </chartareas>

        </asp:Chart>


Step 3: Write the code in Webform1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace Binding_XML_file_to_ASP.NET_Chart_Control
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();

            ds.ReadXml(Server.MapPath("~/Employee.xml"));

            Chart1.Series["Series1"].XValueMember = "EmployeeName";

            Chart1.Series["Series1"].YValueMembers = "Salary";

            Chart1.DataSource = ds;
            Chart1.DataBind();


        }
    }

}


Step 4 : Run the application. The XML data should be displayed in a column chart as shown below.



No comments:

Post a Comment