0
votes

I am using

System.Windows.Forms.DataVisualization.Charting.Chart

reference and I wand to build a chart without chart element in my winform UI , I just want to create a chart with code and store it as an image. but after code runs I got and empty image saved. my code :

    Chart ch = new Chart();
    ch.Series.Add("tt");
    ch.Series["tt"].Points.AddXY(1, 10);
    ch.Series["tt"].Points[0].SetValueY(4);
    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "savedImg.jpg");
    ch.SaveImage(path, ChartImageFormat.Jpeg);

and here is the output : enter image description here

please help me .

1
Looks like you might need to add a chart area as well. Just called before you add your series ch.ChartAreas.Add(new ChartArea()); Also if you wish for a legend to be displayed you need to add that manually as well. ch.Legends.Add(new Legend()); When you add a chart control to a winform all this manual stuff is taken care of in the Designer file, when creating one pro-grammatically you need to do that stuff manually.Bearcat9425
@Bearcat9425 Thanks a lot . solved by adding these two lines , thanks again , you've saved my daymostafa yalpaniyan
Glad I could help.Bearcat9425

1 Answers

1
votes

You need to setup your chart manually when creating a chart control yourself. Things like Chart Areas legends and titles etc are added in through designers in the background. When creating from code you must setup all the details yourself. I tested this code and it produces a image of the chart.

Chart ch = new Chart();
// Edit for your Chart Title
ch.Titles.Add(new Title("chart For Saving"));
// To display your tt series on the legend
ch.Legends.Add(new Legend());
ch.ChartAreas.Add(new ChartArea());
ch.Series.Add("tt");
ch.Series["tt"].Points.AddXY(1, 10);
ch.Series["tt"].Points[0].SetValueY(4);
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "savedImg.jpg");
ch.SaveImage(path, ChartImageFormat.Jpeg);