[英]How to access a chart to add a data point in c#
我正在嘗試編寫 class 來更新圖表數據。 我已經通過 windows forms 創建了圖表,它在 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 的 class,它有一種方法可以在圖中添加一個額外的點
namespace DataLogger
{
class UpdateGraph
{
public void addGraphPoints()
{
chart1.Series.Points.AddXY(0, 10);
}
}
}
問題是我收到消息錯誤
當前上下文中不存在名稱 chart1
因此,如果有人能解釋我如何訪問圖表來修改數據(或者我應該指的是什么),我會非常感激,因為我現在有點難過。
您可以嘗試以下方法:
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);
}
}
Forms Designer將在InitializeComponent()中創建一個本地圖表-也許有一種方法可以阻止它,但是我還沒有找到它。 訣竅是使圖表脫離您的控制層次結構。 例如,將我在Designer.cs中的圖表添加到grpStuff中:
this.grpStuff.Controls.Add(chrtStuff);
其名稱也可以在Designer.cs中找到:
chrtStuff.Name = "chartName";
所以-在我的代碼中,我通過以下方式找到圖表:
chrt = (System.Windows.Forms.DataVisualization.Charting.Chart)grpStuff.Controls("chartName");
chart1.Series["您的系列名稱"].Points.AddXY(0, 10); 抱歉這么快
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.