如何在vb.net中绘制连续线图 [英] How to draw continuous line graph in vb.net
问题描述
我对 VB.NET 很陌生.我正在尝试使用图形 UI 控件根据特定时间间隔绘制连续折线图.我能够第一次绘制图形并在第二次得到未处理的异常.请参考我下面的代码,
I'm very new to VB.NET. I'm trying to draw continuous line graph based on certain time intervals using the graph UI control. I'm able to draw the graph the first time and getting unhandled exception on second time. Please refer to my code below,
Dim s As New Series
s.Name = "aline"
'Change to a line graph.
s.ChartType = SeriesChartType.Line
For index As Integer = 1 To 10
s.Points.AddXY("1990", 27)
s.Points.AddXY("1991", 15)
s.Points.AddXY("1992", index)
Next
Chart1.Series.Add(s)
Threading.Thread.Sleep(1000)
s.Points.AddXY("1993", 27)
s.Points.AddXY("1994", 15)
s.Points.AddXY("1995", 10)
Chart1.Series.Add(s)'Here im getting exception
但是,如果我第二次尝试使用 Chart1.Series.Add(s)
更新值,我会收到名为 'aline' 的图表元素已存在于 '系列集合'"错误.请指导如何持续更新值.
But on second time if I try to update the values using Chart1.Series.Add(s)
, I'm getting "A chart element with the name 'aline' already exists in the 'SeriesCollection'" error. Please guide how to update the values continuously.
推荐答案
您无需执行任何操作即可更新图表 - 只需删除第二个 Chart1.Series.Add(s)
.
You do not need to do anything to get the chart to update - just remove the second Chart1.Series.Add(s)
.
在某些情况下,您可能需要强制更新,在这种情况下,您可以使用 Chart.DataBind 方法.
In some cases, you may need to force an update, in which case you would use the Chart.DataBind method.
来自 DataBind 方法文档的备注部分:
From the Remarks section of the DataBind method documentation:
如果数据源设置为图表并且不需要其他数据操作,则不必显式调用 DataBind 方法.在这些情况下,图表本身会在呈现之前将数据绑定到数据源.
In cases where a data source is set to a chart and no other data operations are required, the DataBind method does not have to be explicitly called. In these cases, the Chart itself will data bind to the data source prior to being rendered.
如果您在表单中添加一个按钮来添加一些值,则更容易看到此操作:当您单击该按钮时,您会看到图表调整其 x 轴并添加新点.
The action of this is easier to see if you add a button to the form to add some values: when you click the button, you see the chart adjust its x-axis and add the new points.
Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Dim s As New Series
Sub DoChart()
s.Name = "aline"
'Change to a line graph.
s.ChartType = SeriesChartType.Line
For index As Integer = 1 To 10
s.Points.AddXY("1990", 27)
s.Points.AddXY("1991", 15)
s.Points.AddXY("1992", index)
Next
Chart1.Series.Add(s)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
s.Points.AddXY("1993", 27)
s.Points.AddXY("1994", 15)
s.Points.AddXY("1995", 10)
'Chart1.DataBind()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DoChart()
End Sub
End Class
这篇关于如何在vb.net中绘制连续线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!