Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

c# - 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.

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
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.

Regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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..

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

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. So Chart needs a little help in finding the x- and y-values..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...