是否可以从通用列表中设置图表数据源? [英] Is it possible to set a chart datasource from a generic list?

查看:23
本文介绍了是否可以从通用列表中设置图表数据源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list created from a linq query that contains 2 columns of data.

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()

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

I'm trying to use the chart control datasource to use that list, but when I call the bind method I receive this error:

System.ArgumentException 未处理 HResult=-2147024809
Message=Series 数据点不支持类型值<>f__AnonymousType0`2[System.Double,System.Decimal] 仅值可以使用这些类型:Double、Decimal、Single、int、long、uint、ulong、字符串、日期时间、短、ushort.

System.ArgumentException was unhandled HResult=-2147024809
Message=Series data points do not support values of type <>f__AnonymousType0`2[System.Double,System.Decimal] only values of these types can be used: 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.

问候.

推荐答案

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

Yes it is possible, but not by binding the list to the Chart itself.

有几种完全不同的方法来执行图表数据绑定,各有优缺点.

There are several quite different methods to do Chart Databinding, all with different sets of pros and cons..

我建议使用 系列.Points.DataBindXYSeries.Points.DataBind 方法.

I suggest using the Series.Points.DataBindXY or Series.Points.DataBind methods.

这是一个例子:

// 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)));

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

Now create a generic list from it:

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", "" );

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

In your case you would write maybe this:

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

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

Note that a Chart typically can only display pairs of values whereas a DGV can create as many columns as the DataSource has. So Chart needs a little help in finding the x- and y-values..

这篇关于是否可以从通用列表中设置图表数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆