Search code examples
c#winformsadditionseriesmschart

C# How to add data to a dynamically added MSChart?


I'm currently trying to add data to my chart that I created dynamically. I've got a class (AddGraph) with following method:

public class AddGraph
{
    public string Name { get; set; }
    Random R = new Random();
    System.Windows.Forms.DataVisualization.Charting.Chart chart_holder = new System.Windows.Forms.DataVisualization.Charting.Chart();
    System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();

    public Panel panelAdd(TableLayoutPanel fp, string hostNameIP)
    {
        Panel p = new Panel();
        p.Name = hostNameIP;
        Name = p.Name;
        p.Anchor = (AnchorStyles.Left | AnchorStyles.Right);
        p.Size = new Size(fp.ClientSize.Width, 100);
        p.Dock = DockStyle.Top;

        //tablelayoutpanel - definition
        fp.Controls.Add(p);
        fp.Controls.SetChildIndex(p, 0);
        fp.HorizontalScroll.Visible = false;
        fp.HorizontalScroll.Maximum = 0;
        fp.AutoScroll = false;
        fp.AutoScroll = true;

        //insert title
        chart_holder.Titles.Add(hostNameIP);
        chart_holder.Titles[0].Alignment = ContentAlignment.TopLeft;

        chart_holder.Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom);
        chart_holder.Size = p.Size;
        chart_holder.ChartAreas.Add(chartArea1);
        chart_holder.Series.Add("Series1");
        chart_holder.BackColor = Color.Transparent;

        chart_holder.Series[0].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
        chart_holder.Series[0].ChartArea = chart_holder.ChartAreas[0].Name;

        chart_holder.ChartAreas[0].BackColor = Color.Transparent;
        chart_holder.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
        chart_holder.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot;

        p.Controls.Add(chart_holder);
        fp.Invalidate();

        return p;
    }
}

In another class (TestForm) I'm creating the panels with the chart like following:

source.AddGraph a = new source.AddGraph();
var createdPanel = a.panelAdd(tableLayoutPanel1, ip);

How can I access now the chart inside the panel and do something like chart_holder.Series[0].Points.AddXY(1,10);


Solution

  • You can search by the name that you gave to the control by using this.

    foreach (Control c in fp.Controls)
    {
        if (c is Chart)
        {
            Chart ChartControl = (Chart)c;
    
            if (ChartControl.Name.Equals("Chart Name"))      
                //Code to modify Chart values
        }
    }
    

    You MUST use this using, to access the Chart Control:

    using System.Windows.Forms.DataVisualization.Charting
    

    Hope this helps!