简体   繁体   English

是否可以从通用列表中设置图表数据源?

[英]Is it possible to set a chart datasource from a generic list?

I have a list created from a linq query that contains 2 columns of data.我有一个从包含 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()

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 was unhandled HResult=-2147024809 System.ArgumentException 未处理 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. Message=Series 数据点不支持 <>f__AnonymousType0`2[System.Double,System.Decimal] 类型的值,只能使用以下类型的值:Double、Decimal、Single、int、long、uint、ulong、String、日期时间,短,超短。

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

Regards.问候。

Yes it is possible, but not by binding the list to the Chart itself.是的,这是可能的,但不能通过将列表绑定到Chart本身。

There are several quite different methods to do Chart Databinding , all with different sets of pros and cons..有几种完全不同的方法可以进行Chart Databinding ,所有方法都有不同的优缺点。

I suggest using the Series.Points.DataBindXY or Series.Points.DataBind methods.我建议使用Series.Points.DataBindXYSeries.Points.DataBind方法。

Here is an example:下面是一个例子:

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

Now this works:现在这有效:

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

or also this:或者这个:

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

In your case you would write maybe this:在您的情况下,您可能会这样写:

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

Note that a Chart typically can only display pairs of values whereas a DGV can create as many columns as the DataSource has.请注意, Chart通常只能显示成对的值,而DGV可以创建与DataSource一样多的列 So Chart needs a little help in finding the x- and y-values..所以Chart需要一点帮助来找到 x 和 y 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM