Create and Use Various Types of Zed Graph Chart in ASP.Net Web Form

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.

  • ZedGraph
  • ZedGraph.Web

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.                 }  
  30.                 cmd.Connection = con;  
  31.                 adp.SelectCommand = cmd;  
  32.                 adp.Fill(dt);  
  33.                 con.Close();  
  34.                 dtemp = dt;  
  35.             }  
  36.         }  
  37.     }  
  38.     public DataTable MarksDetails()  
  39.     {  
  40.         DataTable dt = new DataTable();  
  41.         selectData("SpStudentInfo"out dt, null);  
  42.         return dt;  
  43.     }  
  44. }  
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.   
  9. /// <summary>  
  10. /// Required method for Designer support - do not modify  
  11. /// the contents of this method with the code editor.  
  12. /// </summary>  
  13. private void InitializeComponent()  
  14. {  
  15.     this.ZedGraphWeb1.RenderGraph += new ZedGraph.Web.ZedGraphWebControlEventHandler(this.OnRenderZedGraph);           
  16. }  
  17. #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.      
  4.    switch (ddlChartType .SelectedItem .Text )  
  5.    {  
  6.        case  "Select Chart Type..":  
  7.            ZedGraphWeb1.Visible = false;  
  8.            break;  
  9.        case "Clustered Column":  
  10.            ClusteredColumnsChartDisplay(masterPane, g);  
  11.            break;  
  12.        case "Stacked":  
  13.            StackedChartDisplay(masterPane, g);  
  14.            break;  
  15.        case "Line":  
  16.            LineChartDisplay(masterPane, g);  
  17.            break;  
  18.        case "Pie":  
  19.            PieChartDisplay(masterPane, g);  
  20.            break;  
  21.              
  22.    }  
  23. }  
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.   
  13.     for (int i = 0; i < dt.Rows.Count; i++)  
  14.     {  
  15.         x0[i] = dt.Rows[i]["Name"].ToString();  
  16.         y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);  
  17.     }  
  18.     // Declare a BarItem:- Bar Item is used for creating a bar       
  19.     BarItem myCurve;  
  20.   
  21.     // Generate a blue bar with "Marks1" in the legend  
  22.     myCurve = myPane.AddBar("Marks1", y0, null, Color.Green);  
  23.     // Fill the bar with a Blue-white-Blue color gradient for a 3d look  
  24.     myCurve.Bar.Fill = new Fill(Color.Green, Color.White, Color.Green, 0f);  
  25.     //if you want to drow multiple chat comparing two field then use like that   
  26.     // Generate a red bar with "Marks2" in the legend  
  27.     myCurve = myPane.AddBar("Marks2", y0, null, Color.Yellow );  
  28.     // Fill the bar with a red-white-red color gradient for a 3d look  
  29.     myCurve.Bar.Fill = new Fill(Color.Yellow, Color.White, Color.Yellow, 0f);  
  30.   
  31.     // Set the YAxis labels  
  32.     myPane.YAxis.Scale.TextLabels = x0;  
  33.     // Set the YAxis to Text type  
  34.     myPane.YAxis.Type = AxisType.Text;  
  35.     // Make the bars horizontal by setting the BarBase to "Y"  
  36.     myPane.BarSettings.Base = BarBase.Y;  
  37.     // Fill the axis background with a color gradient  
  38.     myPane.Chart.Fill = new Fill(Color.White, Color.Green , 45.0F);  
  39.   
  40.     masterPane.AxisChange(g);  
  41. }  
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.   
  5.     // Set the title and axis labels          
  6.     myPane.XAxis.Title.Text = "X-Axis";  
  7.     myPane.YAxis.Title.Text = "Y-Axis";  
  8.     DataTable dt = new DataTable();  
  9.     DbOperation db = new DbOperation();  
  10.     dt = db.MarksDetails();  
  11.     string[] x0 = new string[dt.Rows.Count];  
  12.     double[] y0 = new double[dt.Rows.Count];  
  13.   
  14.     for (int i = 0; i < dt.Rows.Count; i++)  
  15.     {  
  16.         x0[i] = dt.Rows[i]["Name"].ToString();  
  17.         y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);  
  18.     }  
  19.   
  20.     // Declare a BarItem:- Bar Item is used for creating a bar       
  21.     BarItem myCurve;  
  22.   
  23.     // Generate a blue bar with "Completed" in the legend  
  24.     myCurve = myPane.AddBar("Completed"null, y0, Color.Red );  
  25.     // Fill the bar with a Blue-white-Blue color gradient for a 3d look  
  26.     myCurve.Bar.Fill = new Fill(Color.Green, Color.White, Color.Red, 0f);  
  27.     // Set the XAxis labels  
  28.     myPane.XAxis.Scale.TextLabels = x0;  
  29.     // Set the XAxis to Text type  
  30.     myPane.XAxis.Type = AxisType.Text;  
  31.     // Make the bars Vertical by setting the BarBase to "X"  
  32.     myPane.BarSettings.Base = BarBase.X;  
  33.     masterPane.AxisChange(g);  
  34. }  
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.   
  13.     for (int i = 0; i < dt.Rows.Count; i++)  
  14.     {  
  15.         x0[i] = dt.Rows[i]["Name"].ToString();  
  16.         y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);  
  17.     }  
  18.   
  19.     // Declare a LineItem:- LineItem is used for creating a line       
  20.     LineItem oLineItem;  
  21.   
  22.     oLineItem = myPane.AddCurve("Marks1", y0, y0, Color.Red, SymbolType.None);  
  23.     //if you want to drow multiple chat comparing two field then use like that     
  24.     oLineItem = myPane.AddCurve("Marks2", y0, y0, Color.Yellow  , SymbolType.None);  
  25.   
  26.     // Set the XAxis labels  
  27.     myPane.XAxis.Scale.TextLabels = x0;  
  28.     // Set the YAxis to Text type  
  29.     myPane.XAxis.Type = AxisType.Text;  
  30.     // Draw the X tics at the labels  
  31.     myPane.XAxis.MajorTic.IsBetweenLabels = false;  
  32.   
  33.     // Fill the axis background with a color gradient  
  34.     myPane.Chart.Fill = new Fill(Color.White, Color.Green  , 45.0F);  
  35.   
  36.     masterPane.AxisChange(g);  
  37. }  
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.   
  5.     // Set the title and axis labels          
  6.     myPane.XAxis.Title.Text = "X-Axis";  
  7.     myPane.YAxis.Title.Text = "Y-Axis";  
  8.     DataTable dt = new DataTable();  
  9.     DbOperation db = new DbOperation();  
  10.     dt = db.MarksDetails();  
  11.     string[] x0 = new string[dt.Rows.Count];  
  12.     double[] y0 = new double[dt.Rows.Count];  
  13.   
  14.     for (int i = 0; i < dt.Rows.Count; i++)  
  15.     {  
  16.         x0[i] = dt.Rows[i]["Name"].ToString();  
  17.         y0[i] = Convert.ToDouble(dt.Rows[i]["Total Marks"]);  
  18.     }  
  19.   
  20.     myPane.Fill = new Fill(Color.White, Color.Red, 45.0f);  
  21.     // No fill for the chart background  
  22.     myPane.Chart.Fill.Type = FillType.None;  
  23.     // Set the legend to an arbitrary location  
  24.     myPane.Legend.Position = LegendPos.Float;  
  25.     myPane.Legend.Location = new Location(0.95f, 0.15f, CoordType.PaneFraction, AlignH.Right, AlignV.Top);  
  26.     myPane.Legend.FontSpec.Size = 10f;  
  27.     // IsHStack is use the create the legend items horizontally  
  28.     myPane.Legend.IsHStack = false;  
  29.     // Add some pie slices  
  30.     for (int i = 0; i < y0.Length; i++)  
  31.     {  
  32.         PieItem segment1 = myPane.AddPieSlice(y0[0], Color.Brown, Color.White, 45f, 0, x0[i]);  
  33.     }  
  34.     masterPane.AxisChange(g);  
  35.     // 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  
  36. }  
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] [intNOT NULL,  
  5.     [Sub2] [intNOT NULL,  
  6.     [Sub3] [intNOT NULL,  
  7.     [Sub4] [intNOT 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  = ONON [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.