winforms 如何在C#中访问图表以添加数据点

gcuhipw9  于 2022-11-17  发布在  C#
关注(0)|答案(3)|浏览(165)

我正在尝试编写一个类来更新图表数据。我已经通过Windows窗体创建了图表,窗体已经自动生成了Form1.cs和Form1.Designer.cs中的代码
下面是我认为Form1.designer.cs中的相关部分:

private void InitializeComponent()
{
    System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
    System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
    System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint1 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 2D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint2 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 3D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint3 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 2D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint4 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 25D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint5 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 2D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint6 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 3D);
    System.Windows.Forms.DataVisualization.Charting.DataPoint dataPoint7 = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D);
    this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
    this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
    this.tableLayoutPanel1.SuspendLayout();
    ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
    this.SuspendLayout();

我编写了另一个名为UpdateGraph.cs的类,它有一个向图形添加额外点的方法

namespace DataLogger
{
    class UpdateGraph
    {
        public void addGraphPoints()
        {
            chart1.Series.Points.AddXY(0, 10);   
        }
    }
}

问题是我收到一个错误消息
当前上下文中不存在名称chart1
因此,如果有人能解释我如何访问图表来修改数据(或者我应该参考什么),我真的会很感激,因为我现在有点难住了。

5jdjgkvh

5jdjgkvh1#

你可以试试这个:

using System.Windows.Forms.DataVisualization.Charting;

class UpdateGraph
{
    public Chart Chart1 { get; set; }

    public UpdateGRaph(Chart chart)
    {
        Chart1 = chart;
    }

    public void AddGraphPoints()
    {
        Chart1.Series.Points.AddXY(0, 10);

    }
}
knpiaxh1

knpiaxh12#

Forms Designer将在InitializeComponent()中创建一个本Map表-也许有一种方法可以阻止它,但我还没有找到它。诀窍是将图表从控件层次结构中取出。例如,我在Designer.cs中的图表被添加到grpStuff中:

this.grpStuff.Controls.Add(chrtStuff);

其名称也可以在Designer.cs中找到:

chrtStuff.Name = "chartName";

因此,在我的代码中,我通过以下方式找到图表:

chrt = (System.Windows.Forms.DataVisualization.Charting.Chart)grpStuff.Controls("chartName");
wtzytmuj

wtzytmuj3#

chart1.Series["Your series name"].Points.AddXY(0, 10);

相关问题