Thursday, March 22, 2012

Chart in Asp.net

In this example i am going to show how to generate charts in  Asp.net using C#



First you have to Download Chart.dll a third party control.

after download.

1 open/create new website in asp.net application.
2. Add referance of chart.dll into application.
    right click on solution explorer>> add reference>>browse>>browse & select    chart.dll then click add.
3. create new file. default.aspx
4. register webchart into default.aspx (html) page
 
<%@ Register TagPrefix="Web" Namespace="WebChart" Assembly="WebChart" %>

5.
add control into page.

<Web:ChartControl runat="server" ID="ChartControl3" Height="400" Width="350" GridLines="none"  Legend-Position="Bottom" />

6. goto default.aspx.cs page &  add namespace
   using System.Drawing;
using System.Data.SqlClient;
using WebChart;



7.

 protected void Page_Load(object sender, EventArgs e)
    {
CreateChart();
}




void CreateChart() {
    PieChart chart = new PieChart();
    chart.DataSource = GetDataSet().Tables[0].DefaultView;
    chart.DataXValueField = "Title";
    chart.DataYValueField = "Price";
    chart.DataLabels.Visible = true;
    chart.DataLabels.ForeColor = System.Drawing.Color.Blue;
    chart.Shadow.Visible = true;
    chart.DataBind();
    chart.Explosion = 10;
    ChartControl1.Charts.Add(chart);
    ChartControl1.RedrawChart();
}
 
DataSet GetDataSet() {
    DataSet ds = new DataSet();
    DataTable table = ds.Tables.Add("My Table");
    table.Columns.Add(new DataColumn("Title"));
    table.Columns.Add(new DataColumn("Price", typeof(int)));
 
    Random rnd = new Random();
    for (int i = 0; i < 10; i++) {
        DataRow row = table.NewRow();
        row["Title"] = "Title:" + i.ToString();
        row["Price"] = rnd.Next(1, 100);
        table.Rows.Add(row);
    }
    return ds;
}

No comments:

Post a Comment