Introduction

ZedGraph is a class library, user control and web control for .Net written in C# for drawing 2D Line, Bar and Pie Charts. It features full, detailed customization capabilities, but most options have defaults for ease of use. It's very easy to create the various types of Zed Graph charts in ASP.NET.

You can download the ZED Graph library by downloading the sample code or Click here.

After downloading the reference add it to Visual Studio Toolbar using the following procedure.

Step 1

Open Visual Studio and create a new web application. Open the toolbar and right-click on it.

add tab

Step 2

Select the Add Tab and give the name “ZedGraph Controls ”. Now right-click on that tab.

choose items

Step 3

Select Choose Items. Then the following window appears.

access data source

Step 4

Click Browse and select the Zed Graph DLL path and select it.

dll file

Step 5

Select Open then click OK and continue. Now the ZedGraph controls have been added to your toolbar.

Step 6

Then you also need to copy one image DLL and paste it into your project. You can download that image file from the source code and name it “ZedGraphImages”.

Step 7

Check in the reference tab, the following two references are added but if not and it is missing then add it again by selecting the ZedGraph DLL.

Step 8

Drag and drop a DropDownList toolbar and add some list items as in the following:

  1. <asp:DropDownList ID="ddlChartType" runat="server" Height="25px" Width="171px" AutoPostBack="True">
  2. <asp:ListItem>Select Chart Type..</asp:ListItem>
  3. <asp:ListItem>Clustered Column</asp:ListItem>
  4. <asp:ListItem>Stacked</asp:ListItem>
  5. <asp:ListItem>Line</asp:ListItem>
  6. <asp:ListItem>Pie</asp:ListItem>
  7. </asp:DropDownList>

Step 9

Drag and drop a ZedGraphWeb from the toolbar. When you drop it to the page it will add the following reference and some code on the page automatically.

  1. <%@ Register Assembly="ZedGraph.Web" Namespace="ZedGraph.Web" TagPrefix="manish" %>
  2. <manish:ZedGraphWeb ID="ZedGraphWeb1" runat="server"></manish:ZedGraphWeb>
Step 10

Now create a class that will communicate with the database and call the Stored Procedure for displaying the chart.
  1. public class Configuration
  2. {
  3. internal static string connectionString = ConfigurationManager.ConnectionStrings["DbCS"].ConnectionString;
  4. }
  5. public class DbOperation
  6. {
  7. private void selectData(string StoredProcedureName, out DataTable dtemp, [Optional] string[,] aryParameters)
  8. {
  9. using (SqlConnection con = new SqlConnection(Configuration.connectionString))
  10. {
  11. using (SqlCommand cmd = new SqlCommand())
  12. {
  13. con.Open();
  14. cmd.CommandType = CommandType.StoredProcedure;
  15. SqlDataAdapter adp = new SqlDataAdapter();
  16. DataTable dt = new DataTable();
  17. cmd.CommandText = StoredProcedureName;
  18. cmd.CommandTimeout = 300;
  19. try
  20. {
  21. for (int i = 0; i < aryParameters.GetLength(0); i++)
  22. {
  23. cmd.Parameters.Add(new SqlParameter(aryParameters[i, 0], aryParameters[i, 1]));
  24. }
  25. }
  26. catch (Exception ex)
  27. {
  28. }
  29. cmd.Connection = con;
  30. adp.SelectCommand = cmd;
  31. adp.Fill(dt);
  32. con.Close();
  33. dtemp = dt;
  34. }
  35. }
  36. }
  37. public DataTable MarksDetails()
  38. {
  39. DataTable dt = new DataTable();
  40. selectData("SpStudentInfo", out dt, null);
  41. return dt;
  42. }
  43. }
Step 11

Now go to the code behind of the web form and write some code and a function.

Note: For displaying the Zed Graph we need to use the following method of ZedGraph.

this.ZedGraphWeb1.RenderGraph += new ZedGraph.Web.ZedGraphWebControlEventHandler(this.OnRenderZedGraph);

And call this method to the OnInit method of your web page.

Step 12

The code structure of your code behind will be as follows.
  1. #region ZedGraphWeb Display
  2. override protected void OnInit(EventArgs e)
  3. {
  4. // This call is required by the ASP.NET Web Form Designer.
  5. InitializeComponent();
  6. base.OnInit(e);
  7. }
  8. /// <summary>
  9. /// Required method for Designer support - do not modify
  10. /// the contents of this method with the code editor.
  11. /// </summary>
  12. private void InitializeComponent()
  13. {
  14. this.ZedGraphWeb1.RenderGraph += new ZedGraph.Web.ZedGraphWebControlEventHandler(this.OnRenderZedGraph);
  15. }
  16. #endregion
Note: The OnRenderZedGraph contains the code that will create the various types of graphs and initialize the x-axis and y-axis data of the graph by selecting it from our database. This method will contain the following function calls.

  1. ClusteredColumnsChartDisplay: For displaying a Clustered Columns Chart.

  2. StackedChartDisplay: For displaying a Stacked Chart.

  3. LineChartDisplay: For displaying a Line Chart.

  4. PieChartDisplay: For displaying a Pie Chart.

Function Structure

  1. private void OnRenderZedGraph(ZedGraph.Web.ZedGraphWeb z, System.Drawing.Graphics g, ZedGraph.MasterPane masterPane)
  2. {
  3. switch (ddlChartType .SelectedItem .Text )
  4. {
  5. case "Select Chart Type..":
  6. ZedGraphWeb1.Visible = false;
  7. break;
  8. case "Clustered Column":
  9. ClusteredColumnsChartDisplay(masterPane, g);
  10. break;
  11. case "Stacked":
  12. StackedChartDisplay(masterPane, g);
  13. break;
  14. case "Line":
  15. LineChartDisplay(masterPane, g);
  16. break;
  17. case "Pie":
  18. PieChartDisplay(masterPane, g);
  19. break;
  20. }
  21. }
Step 13

For creating a chart we basically need two columns, one will represent the x-axis and the other will represent the y-axis. The same is required with the ZedGraph chart also.

Note: For showing y-axis data in ZedGraph only double data array is needed.

Step 14

Write the following function to create a Clustered Columns Chart.
  1. void ClusteredColumnsChartDisplay(ZedGraph.MasterPane masterPane, System.Drawing.Graphics g)
  2. {
  3. GraphPane myPane = masterPane[0];
  4. // Set the title and axis labels
  5. myPane.XAxis.Title.Text = "X-Axis";
  6. myPane.YAxis.Title.Text = "Y-Axis";
  7. DataTable dt = new DataTable();
  8. DbOperation db = new DbOperation();
  9. dt = db.MarksDetails();
  10. string[] x0 = new string[dt.Rows.Count];
  11. double[] y0 = new double[dt.Rows.Count];
  12. for (int i = 0; i < dt.Rows.Count; i++)
  13. {
  14. x0[i] = dt.Rows[i]["Name"].ToString();
  15. y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);
  16. }
  17. // Declare a BarItem:- Bar Item is used for creating a bar
  18. BarItem myCurve;
  19. // Generate a blue bar with "Marks1" in the legend
  20. myCurve = myPane.AddBar("Marks1", y0, null, Color.Green);
  21. // Fill the bar with a Blue-white-Blue color gradient for a 3d look
  22. myCurve.Bar.Fill = new Fill(Color.Green, Color.White, Color.Green, 0f);
  23. //if you want to drow multiple chat comparing two field then use like that
  24. // Generate a red bar with "Marks2" in the legend
  25. myCurve = myPane.AddBar("Marks2", y0, null, Color.Yellow );
  26. // Fill the bar with a red-white-red color gradient for a 3d look
  27. myCurve.Bar.Fill = new Fill(Color.Yellow, Color.White, Color.Yellow, 0f);
  28. // Set the YAxis labels
  29. myPane.YAxis.Scale.TextLabels = x0;
  30. // Set the YAxis to Text type
  31. myPane.YAxis.Type = AxisType.Text;
  32. // Make the bars horizontal by setting the BarBase to "Y"
  33. myPane.BarSettings.Base = BarBase.Y;
  34. // Fill the axis background with a color gradient
  35. myPane.Chart.Fill = new Fill(Color.White, Color.Green , 45.0F);
  36. masterPane.AxisChange(g);
  37. }
Step 15

Write the following function to create a Stacked Chart.
  1. void StackedChartDisplay(ZedGraph.MasterPane masterPane, System.Drawing.Graphics g)
  2. {
  3. GraphPane myPane = masterPane[0];
  4. // Set the title and axis labels
  5. myPane.XAxis.Title.Text = "X-Axis";
  6. myPane.YAxis.Title.Text = "Y-Axis";
  7. DataTable dt = new DataTable();
  8. DbOperation db = new DbOperation();
  9. dt = db.MarksDetails();
  10. string[] x0 = new string[dt.Rows.Count];
  11. double[] y0 = new double[dt.Rows.Count];
  12. for (int i = 0; i < dt.Rows.Count; i++)
  13. {
  14. x0[i] = dt.Rows[i]["Name"].ToString();
  15. y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);
  16. }
  17. // Declare a BarItem:- Bar Item is used for creating a bar
  18. BarItem myCurve;
  19. // Generate a blue bar with "Completed" in the legend
  20. myCurve = myPane.AddBar("Completed", null, y0, Color.Red );
  21. // Fill the bar with a Blue-white-Blue color gradient for a 3d look
  22. myCurve.Bar.Fill = new Fill(Color.Green, Color.White, Color.Red, 0f);
  23. // Set the XAxis labels
  24. myPane.XAxis.Scale.TextLabels = x0;
  25. // Set the XAxis to Text type
  26. myPane.XAxis.Type = AxisType.Text;
  27. // Make the bars Vertical by setting the BarBase to "X"
  28. myPane.BarSettings.Base = BarBase.X;
  29. masterPane.AxisChange(g);
  30. }
Step 16

Write the following function to create a Line Chart.
  1. void LineChartDisplay(ZedGraph.MasterPane masterPane, System.Drawing.Graphics g)
  2. {
  3. GraphPane myPane = masterPane[0];
  4. // Set the title and axis labels
  5. myPane.XAxis.Title.Text = "X-Axis";
  6. myPane.YAxis.Title.Text = "Y-Axis";
  7. DataTable dt = new DataTable();
  8. DbOperation db = new DbOperation();
  9. dt = db.MarksDetails();
  10. string[] x0 = new string[dt.Rows.Count];
  11. double[] y0 = new double[dt.Rows.Count];
  12. for (int i = 0; i < dt.Rows.Count; i++)
  13. {
  14. x0[i] = dt.Rows[i]["Name"].ToString();
  15. y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);
  16. }
  17. // Declare a LineItem:- LineItem is used for creating a line
  18. LineItem oLineItem;
  19. oLineItem = myPane.AddCurve("Marks1", y0, y0, Color.Red, SymbolType.None);
  20. //if you want to drow multiple chat comparing two field then use like that
  21. oLineItem = myPane.AddCurve("Marks2", y0, y0, Color.Yellow , SymbolType.None);
  22. // Set the XAxis labels
  23. myPane.XAxis.Scale.TextLabels = x0;
  24. // Set the YAxis to Text type
  25. myPane.XAxis.Type = AxisType.Text;
  26. // Draw the X tics at the labels
  27. myPane.XAxis.MajorTic.IsBetweenLabels = false;
  28. // Fill the axis background with a color gradient
  29. myPane.Chart.Fill = new Fill(Color.White, Color.Green , 45.0F);
  30. masterPane.AxisChange(g);
  31. }
Step 17

Write the following function to create a Pie Chart.
  1. void PieChartDisplay(ZedGraph.MasterPane masterPane, System.Drawing.Graphics g)
  2. {
  3. GraphPane myPane = masterPane[0];
  4. // Set the title and axis labels
  5. myPane.XAxis.Title.Text = "X-Axis";
  6. myPane.YAxis.Title.Text = "Y-Axis";
  7. DataTable dt = new DataTable();
  8. DbOperation db = new DbOperation();
  9. dt = db.MarksDetails();
  10. string[] x0 = new string[dt.Rows.Count];
  11. double[] y0 = new double[dt.Rows.Count];
  12. for (int i = 0; i < dt.Rows.Count; i++)
  13. {
  14. x0[i] = dt.Rows[i]["Name"].ToString();
  15. y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);
  16. }
  17. myPane.Fill = new Fill(Color.White, Color.Red, 45.0f);
  18. // No fill for the chart background
  19. myPane.Chart.Fill.Type = FillType.None;
  20. // Set the legend to an arbitrary location
  21. myPane.Legend.Position = LegendPos.Float;
  22. myPane.Legend.Location = new Location(0.95f, 0.15f, CoordType.PaneFraction, AlignH.Right, AlignV.Top);
  23. myPane.Legend.FontSpec.Size = 10f;
  24. // IsHStack is use the create the legend items horizontally
  25. myPane.Legend.IsHStack = false;
  26. // Add some pie slices
  27. for (int i = 0; i < y0.Length; i++)
  28. {
  29. PieItem segment1 = myPane.AddPieSlice(y0[0], Color.Brown, Color.White, 45f, 0, x0[i]);
  30. }
  31. masterPane.AxisChange(g);
  32. // There is no need for pie chart to adjust X and Y axis. So the rest of the code is irrelavent with regard to Pie Chart
  33. }
Step 18

Now the coding is over, compile and run the project to see the output that will be like the following.

  1. Clustered Columns Chart

    Clustered Columns Chart

  2. Stacked Chart

    Stacked Chart

  3. Line Chart

    Line Chart

  4. Pie Chart

    Pie Chart

Note: For this application I am using the following table and Stored Procedure.

tblStudentInfo

  1. CREATE TABLE [dbo].[tblStudentInfo](
  2. [Id] [int] IDENTITY(1,1) NOT NULL,
  3. [Name] [varchar](50) NOT NULL,
  4. [Sub1] [int] NOT NULL,
  5. [Sub2] [int] NOT NULL,
  6. [Sub3] [int] NOT NULL,
  7. [Sub4] [int] NOT NULL,
  8. CONSTRAINT [PK_tblStudentInfo] PRIMARY KEY CLUSTERED
  9. (
  10. [Id] ASC
  11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  12. ) ON [PRIMARY]
This table contains information about student's Marks.

And a Stored Procedure SpStudentInfo calculates the student-wise sum of their marks that I will display in the chart.
  1. in chart.
  2. USE [manishDB]
  3. GO
  4. /****** Object: StoredProcedure [dbo].[SelectAllStudent] Script Date: 11/26/2014 22:26:13 ******/
  5. SET ANSI_NULLS ON
  6. GO
  7. SET QUOTED_IDENTIFIER ON
  8. GO
  9. Create PROCEDURE [dbo].[SpStudentInfo]
  10. AS
  11. Begin
  12. select Top 10 Name,Sub1 +Sub2 +Sub3 +Sub4 "Total Marks"
  13. from tblStudentInfo
  14. End
Summary

In this illustration you came to understand the various types of ZedGraph Chart in ASP.NET.