C#如何将数据添加到动态添加的MSChart中?

时间:2018-04-19 12:51:48

标签: c# winforms add series mschart

我正在尝试将数据添加到我动态创建的图表中。我有一个类(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;
    }
}

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

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

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

之类的操作

1 个答案:

答案 0 :(得分:0)

您可以使用此功能按照您为控件提供的名称进行搜索

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 System.Windows.Forms.DataVisualization.Charting

希望这有帮助!