【问题标题】:Is it possible to set a chart datasource from a generic list?是否可以从通用列表中设置图表数据源?
【发布时间】:2016-10-11 13:47:00
【问题描述】:

我有一个从包含 2 列数据的 linq 查询创建的列表。

var result = root.Descendants().Elements("sensor")
                 .Where(el => (string)el.Attribute("name") == "Sensor1") 
                 .Elements("evt") 
                 .Select(el => new { t1 = el.Attribute("time").Value, 
                                     v1 = el.Attribute("val").Value }) 
                 .ToList()

我正在尝试使用图表控件数据源来使用该列表,但是当我调用绑定方法时收到此错误:

System.ArgumentException 未处理 HResult=-2147024809
消息=系列数据点不支持类型值 f__AnonymousType0`2[System.Double,System.Decimal] 仅值 可以使用这些类型:Double、Decimal、Single、int、long、uint、 ulong、String、DateTime、short、ushort。

//result is a generic list defined as var result = root.Descendants()
chart1.DataSource = result;
chart1.DataBind(); // This is line that causes the exception.

问候。

【问题讨论】:

  • 我们需要查看 linq。
  • var result = root.Descendants() .Elements("sensor") .Where(el => (string)el.Attribute("name") == "Sensor1") .Elements("evt") .Select(el => new { t1 = el.Attribute("time").Value, v1 = el.Attribute("val").Value }) .ToList()
  • 我可以在Datagrid中显示数据,但无法使用图表控件。
  • 查看我的更新答案!

标签: c# linq data-binding charts


【解决方案1】:

是的,这是可能的,但不能通过将列表绑定到 Chart 本身。

Chart Databinding 有几种完全不同的方法,各有优缺点。

我建议使用Series.Points.DataBindXYSeries.Points.DataBind 方法。

这是一个例子:

// create a list with test data:
List<PointF> points = new List<PointF>();
for (int i = 0; i < 100; i++) points.Add(new PointF(i, 1f * i / 2f * R.Next(8)));

现在从中创建一个通用列表:

var al = points.Select(x => new { t1 = x.X, v1 = x.Y }).ToList();

现在可以了:

someSeries.Points.DataBindXY(al, "t1", al, "v1");

或者这个:

someSeries.DataBind(al, "t1", "v1", "" );

在你的情况下,你可能会这样写:

chart1.Series[0].Points.DataBind(result, "t1", "v1");

请注意,Chart 通常只能显示 值,而 DGV 可以创建 DataSource 一样多的列。所以Chart 需要一点帮助才能找到 x 和 y 值..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    相关资源
    最近更新 更多