Tuesday, December 2, 2008

C# Howto: Create a quick Pie Chart with the NEW <asp:chart> control for .Net 4.0

As Scott Guthrie explained on his blog, how to get this new slick asp:chart control. I figured I'd post a simple code example.

I basically have an Orders table that I want to count the number of orders for each vendor to create the above super snazzy Pie Chart...IN 3-D!!!!

Here's my .aspx:
<asp:Chart ID="Chart1" runat="server">
<Series>
<asp:Series Name="Series1" ChartType="Pie">
</asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Name="ChartArea1">
<Area3DStyle Enable3D="True" Inclination="40" />
</asp:ChartArea>
</ChartAreas>
</asp:Chart>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT VendorName, COUNT(*) AS Cnt FROM Orders GROUP BY VendorName">
</asp:SqlDataSource>

Here's my C#:
protected void Page_Load(object sender, EventArgs e)
{
Chart1.DataSource = SqlDataSource1;
Chart1.Series["Series1"].XValueMember ="VendorName";
Chart1.Series["Series1"].YValueMembers = "Cnt";
Chart1.DataBind();
}


Enjoy!!

2 comments:

seeking-solitude said...

Please pardon my ignorance ... but how do you include the lib files... i get an error saying unknown server tag asp:Chart

Thanks

Brad Oyler said...

Assuming you have installed the mschart.exe, the assembly references should get automatically added to your web.config when u drag the control to a aspx page.