ZedGraph C# Graph Data Export to CSV Using a Custom Context Menu

In continuation of my earlier post on ZedGraph example which plots a sinosoidal graph, I have extended it further to:

Add a new custom menu item in context menu(which appears on right click on the graph)

Export Graph plot data to CSV (coma separated values) file. Which can be opened by spreadsheets such as Microsoft Excel and Open Office calc.

For the custom context menu, the code has been derived from ZedGraph Wikipage. The following is the code of the Windows Form which has the ZedGraph control.

[sourcecode language=’c#’]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ZedGraph;
using System.IO;

namespace ZedGraphTest
{
public partial class Form1 : Form
{
private PointPairList m_pointPairList;
//CSV Writer
private StreamWriter m_CSVWriter;

public Form1()
{
InitializeComponent();
CreateGraph();
SetSize();

//csv
zedGraphControl.ContextMenuBuilder +=
new ZedGraphControl.ContextMenuBuilderEventHandler(MyContextMenuBuilder);
}

private void CreateGraph()
{
GraphPane myPane = zedGraphControl.GraphPane;

// Set the titles and axis labels
myPane.Title.Text = “ZedGraph Test”;
myPane.XAxis.Title.Text = “theta (angle)”;
myPane.YAxis.Title.Text = “Sin (theta)”;

// Make up some data points from the Sine function
m_pointPairList = new PointPairList();
for (double x = 0; x <= 360; x += 10) { double y = Math.Sin(x * Math.PI / 180.0); m_pointPairList.Add(x, y); } // Generate a blue curve with Plus symbols, LineItem _myCurve1 = myPane.AddCurve("Sin (theta)", m_pointPairList, Color.Blue, SymbolType.Plus); // Fill the pane background with a color gradient myPane.Fill = new Fill(Color.White, Color.FromArgb(220, 220, 255), 45F); //Make the MajorGrids of Axes visible myPane.XAxis.MajorGrid.IsVisible = true; myPane.YAxis.MajorGrid.IsVisible = true; // Calculate the Axis Scale Ranges zedGraphControl.AxisChange(); } private void Form1_Resize(object sender, EventArgs e) { SetSize(); } private void SetSize() { zedGraphControl.Location = new Point(10, 10); // Leave a small margin around the outside of the control zedGraphControl.Size = new Size(this.ClientRectangle.Width - 20, this.ClientRectangle.Height - 20); } private void MyContextMenuBuilder(ZedGraphControl control, ContextMenuStrip menuStrip, Point mousePt, ZedGraphControl.ContextMenuObjectState objState) { // create a new menu item ToolStripMenuItem _item = new ToolStripMenuItem(); // This is the user-defined Tag so you can find this menu item later if necessary _item.Name = "Export Data as CSV"; _item.Tag = "export_data_csv"; // This is the text that will show up in the menu _item.Text = "Export Data as CSV"; // Add a handler that will respond when that menu item is selected _item.Click += new System.EventHandler(ShowSaveAsForExportCSV); // Add the menu item to the menu,as 3rd Item menuStrip.Items.Insert(2, _item); } private void ShowSaveAsForExportCSV(object sender, System.EventArgs e) { try { //show saveAs CmdDlg saveFileDialog1.Filter = "CSV files (*.csv)|*.csv"; saveFileDialog1.ShowDialog(); m_CSVWriter = new StreamWriter(saveFileDialog1.FileName); WriteCSVToStream(); m_CSVWriter.Close(); MessageBox.Show("CSV File Saved", " ZedGraph ", MessageBoxButtons.OK); } catch (Exception ex) { m_CSVWriter.Close(); MessageBox.Show(ex.ToString()); } } private void WriteCSVToStream() { //First line is for Headers., X and Y Axis string _xAxisHeader = CheckCSVString(zedGraphControl.GraphPane.XAxis.Title.Text); string _yAxisHeader = CheckCSVString(zedGraphControl.GraphPane.YAxis.Title.Text); m_CSVWriter.Write(_xAxisHeader + "," + _yAxisHeader + "n"); //subsequent lines are having data for (int i = 0; i < m_pointPairList.Count; i++) { m_CSVWriter.Write(m_pointPairList[i].X + "," + m_pointPairList[i].Y + "n"); } } private string CheckCSVString(string _string) {//Check to see if there are any characters that can disturb the CSV delimeters. string _returnString = _string; if (_string.IndexOfAny("",x0Ax0D".ToCharArray()) > -1)
{
_returnString = “”” + _string.Replace(“””, “”””) + “””;
}
return _returnString;
}

}
}

[/sourcecode]