Как создать диаграмму MSChartObject из кода?

Question: Как создать диаграмму MSChartObject из кода?

Answer:

1. Создайте новый объект MSChart, установите высоту, ширину,и легенду:

1
2
3
4
MSChartObject MSChart1 = new MSChartObject();
 MSChart1.Width = 300;
 MSChart1.Height = 300;
 MSChart1.Chart.Legends.Add(new Legend() { Name = "Legend1", Title="Legend title"});

 2. Создайте объект ChartArea, установите  имя, названия осей и назначьте созданный объект MSChart:

1
2
3
4
5
ChartArea chartArea1 = new ChartArea();
 chartArea1.Name = "ChartArea1";
 chartArea1.Axes[0].Title = "X name";
 chartArea1.Axes[1].Title = "Y name";
 MSChart1.Chart.ChartAreas.Add(chartArea1);

3. Создайте объект Series, установите тип диаграммы, толщину границы, добавьте точки и назначьте серии диаграмме:

1
2
3
4
5
6
7
8
9
 Series series = new Series("sample");
 series.ChartType = SeriesChartType.Line;
 series.BorderWidth = 2;
 series.Points.Add(new DataPoint(0, 1));
 series.Points.Add(new DataPoint(1, 2));
 series.Points.Add(new DataPoint(3, 5));
 series.Points.Add(new DataPoint(4, 8));
 
 MSChart1.Chart.Series.Add(series);

 4. Присвойте созданный MSChart объекту отчёта DataBand:

1
2
3
4
5
Report report = new Report();
report.Load("ok.frx");
DataBand db = report.FindObject("Data1") as DataBand;
 
MSChart1.Parent = db;

 И полный фрагмент кода:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 MSChartObject MSChart1 = new MSChartObject();
 MSChart1.Width = 300;
 MSChart1.Height = 300;
 MSChart1.Chart.Legends.Add(new Legend() { Name = "Legend1", Title="Legend title"});
 
 ChartArea chartArea1 = new ChartArea();
 chartArea1.Name = "ChartArea1";
 chartArea1.Axes[0].Title = "X name";
 chartArea1.Axes[1].Title = "Y name";
 MSChart1.Chart.ChartAreas.Add(chartArea1); 
 
 Series series = new Series("sample");
 series.ChartType = SeriesChartType.Line;
 series.BorderWidth = 2;
 series.Points.Add(new DataPoint(0, 1));
 series.Points.Add(new DataPoint(1, 2));
 series.Points.Add(new DataPoint(3, 5));
 series.Points.Add(new DataPoint(4, 8));
 
 MSChart1.Chart.Series.Add(series);
 
 Report report = new Report();
 report.Load("ok.frx");
 DataBand db = report.FindObject("Data1") as DataBand;
 MSChart1.Parent = db;

 Результат:
MSChart