C# 如何向动态添加的 MSChart 添加数据?

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

我目前正在尝试将数据添加到我动态创建的图表中。我有一个 class (AddGraph),方法如下:

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;
    }
}

在另一个 class (TestForm) 中,我正在使用如下图表创建面板:

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

现在如何访问面板内的图表并执行类似 chart_holder.Series[0].Points.AddXY(1,10);

的操作

您可以通过使用此控件提供的名称进行搜索。

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
    }
}

必须使用此using来访问图表 控制:

using System.Windows.Forms.DataVisualization.Charting

希望对您有所帮助!