2

I want to use the System.Web.Helpers.Chart in my project. I simply tried the example from the docs:

https://learn.microsoft.com/en-us/aspnet/web-pages/overview/data/7-displaying-data-in-a-chart

var myChart = new Chart(width: 600, height: 400)
        .AddTitle("Chart Title")
        .AddSeries(
            name: "Employee",
            xValue: new[] {  "Peter", "Andrew", "Julie", "Mary", "Dave" },
            yValues: new[] { "2", "6", "4", "5", "3" });

But when I run my code I get the following error:

System.ArgumentNullException: 'Value cannot be null. Parameter name: httpContext'

My code is inside a DLL, not an MVC or WebAPI project. So I guess it lacks a HttpContext for that reason.

Is there still a way to use this Chart library from my DLL project?

Vivendi
  • 20,047
  • 25
  • 121
  • 196
  • Do you have to use the System.Web.Helpers.Chart library? There are data visualization libraries for forms. – Lucax May 25 '18 at 10:11

1 Answers1

3

You would need to reference System.Drawing, System.Windows.Forms and System.Windows.Forms.DataVisualization.

Here's the snippet that builds a bar chart (you can choose whatever type you need) from the data you provided in the example, and saves it locally to a file.

using System.Drawing;
using System.Windows.Forms.DataVisualization.Charting;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var chart = new Chart()
            {
                Size = new Size(600, 400),
                Titles = { "Chart Title" }
            };
            var series = new Series("Employee");
            series.ChartType = SeriesChartType.Bar;
            series.Points.DataBindXY(new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" }, new[] { 2, 6, 4, 5, 3 });

            chart.ChartAreas.Add(new ChartArea());
            chart.Series.Add(series);
            chart.SaveImage("TestChart.png", ChartImageFormat.Png);
        }
    }
}        
buxter
  • 583
  • 4
  • 14
  • That creates a chart and even got accepted, but does it answer the op, which was about _How to use System.Web.Helpers.Chart in DLL_? – TaW May 25 '18 at 13:49
  • I guess the question was, not about how to use specifically System.Web.Helpers.Chart, but rather how to draw a chart in the DLL. At least, that was my perception of the question. Anyway, if the answer was accepted, I believe it solved the OP's problem. – buxter May 25 '18 at 14:19