如何在vb.net中使用单个数据表创建多线图

时间:2018-02-15 09:28:58

标签: sql-server vb.net

我正在开发vb.net应用程序,我必须创建一个多线图。使用存储过程来自数据库的表是: -

TagName   On   Off   Trip
  P1      0     0     1
  P2      0     1     1
  P3      0     1     0
  Q1      0     1     0
  Q2      1     0     1
  Q3      2     2     2
  W1      4     2     1
  W2      2     0     1
  W3      1     1     0
  W4      0     1     1
  W5      2     1     1

我用来绑定名为“chTrend”的图表的vb.net中的代码是: -

ds = ObjTags.GetTrendData()
If (ds.Tables(0).Rows.Count > 0) Then

    dt = ds.Tables(0)
    chTrend.DataSource = dt
    chTrend.Series(0).XValueMember = "TagName"
    chTrend.Series(0).YValueMembers = "On"

    chTrend.Series(1).XValueMember = "TagName"
    chTrend.Series(1).YValueMembers = "Off"

    chTrend.Series(1).XValueMember = "TagName"
    chTrend.Series(1).YValueMembers = "Trip"

    For i = 0 To 2
       chTrend.Series(i).ChartType = SeriesChartType.Line
       chTrend.Series(i).IsVisibleInLegend = True
       chTrend.Series(i).IsValueShownAsLabel = True
       chTrend.Series(i).ToolTip = "Data Point Y Value #VALY{G}"
       chTrend.Series(i).BorderWidth = 3
    Next
End If

当我运行程序时,错误将如下所示

"Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"

位置
chTrend.Series(0).XValueMember = "TagName"

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

假设您的DataTable只有四个DataColumns {TagName,On。关闭。跳转},然后将所示代码中的所有内容替换为以下行:

chTrend.DataSource = dt

有了这个。

chTrend.Series.Clear() ' clears any existing series
Dim s As Series
For columnIndex As Int32 = 1 To dt.Columns.Count - 1
    Dim name As String = dt.Columns(columnIndex).ColumnName
    s = chTrend.Series.Add(name)
    s.XValueMember = dt.Columns(0).ColumnName
    s.YValueMembers = name
    s.ChartType = SeriesChartType.Line
    s.IsVisibleInLegend = True
    s.IsValueShownAsLabel = True
    s.ToolTip = "Data Point Y Value #VALY{G}"
    s.BorderWidth = 3
Next
chTrend.DataBind() ' loads the data from dt to the chart

图表数据绑定不是正常绑定意义上的绑定。您需要告诉图表从源复制数据,以便绘制内容。这就是DataBind方法的作用。