Binding data to Chart control using DataSource property is similar to how we bind data to any databound control (GridView, DropDownList etc) in asp.net
step 1: Create TblEmployee table
Step 3: Modify the Html code in Webform1.aspx
step 4 : write code in Webform1.aspx.cs file
step 1: Create TblEmployee table
Create Table TblEmployee
(
ID int primary key identity,
EmployeeName nvarchar(50),
Salary int
)
insert into TblEmployee values('Srinath',50000)
insert into TblEmployee values('Naveen',60000)
insert into TblEmployee values('Krishna',70000)
step 2: add connectionstring in web.config file
step 2: add connectionstring in web.config file
<connectionStrings>
<add name="DBCS" connectionString="Data
Source=SRINATH-PC\SQLEXPRESS;Initial Catalog=ChartAsp;User
ID=sa;Password=alekhya"/>
</connectionStrings>
<table style="border: 1px solid black; font-family: Arial">
<tr>
<td>
<b>Select Chart Type:</b>
</td>
<td>
<asp:DropDownList ID="DropDownList1"
AutoPostBack="true"
runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Chart ID="Chart1" runat="server">
<Titles><asp:Title Text="Employee
Information" ></asp:Title></Titles>
<series>
<asp:Series Name="Series1"
ChartArea="ChartArea1"
ChartType="Pie">
</asp:Series>
</series>
<chartareas>
<asp:ChartArea Name="ChartArea1">
<AxisX Title="Employee
Names"></AxisX>
<AxisY Title="Salary"></AxisY>
</asp:ChartArea>
</chartareas>
</asp:Chart>
</td>
</tr>
</table>
step 4 : write code in Webform1.aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.DataVisualization.Charting;
using System.Configuration;
using System.Data.SqlClient;
namespace Settingcharttypepropertydynamically
{
public partial class WebForm1 :
System.Web.UI.Page
{
protected void
Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetChartData();
GetChartTypes();
}
}
private void
GetChartData()
{
string connection = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection
con=new SqlConnection(connection))
{
SqlCommand cmd = new SqlCommand("select EmployeeName,Salary from TblEmployee",
con);
con.Open();
SqlDataReader rdr =
cmd.ExecuteReader();
if (rdr.HasRows)
{
Chart1.Series["Series1"].XValueMember
= "EmployeeName";
Chart1.Series["Series1"].YValueMembers
= "Salary";
Chart1.DataSource = rdr;
Chart1.DataBind();
}
}
}
private void
GetChartTypes()
{
foreach (int
chartType in Enum.GetValues(typeof(SeriesChartType)))
{
ListItem li = new ListItem(Enum.GetName(typeof(SeriesChartType),
chartType), chartType.ToString());
DropDownList1.Items.Add(li);
}
}
protected void
DropDownList1_SelectedIndexChanged(object
sender, EventArgs e)
{
GetChartData();
this.Chart1.Series["Series1"].ChartType = (SeriesChartType)Enum.Parse(
typeof(SeriesChartType),
DropDownList1.SelectedValue);
}
}
}
Run the Application
.png)
No comments:
Post a Comment