c# how to add strings to a list so that they will be accessible from DataSource
i am doing this:
List<string> list = new List<开发者_StackOverflowstring>();
while (myReader.Read())
{
reporttime = (string)myReader["reporttime"];
datapath = (string)myReader["datapath"];
list.Add(reporttime,datapath);
}
chart1.DataSource = list;
i am not exactly sure how i should be donig the list.Add
in order to be able to do the following:
chart1.Series["Series1"].XValueMember = "reporttime";
chart1.Series["Series1"].YValueMembers = "datapath";
question: how should i be adding the items to the list?
It might work simply by doing
chart1.DataSource = myReader;
chart1.Series["Series1"].XValueMember = "reporttime";
chart1.Series["Series1"].YValueMembers = "datapath";
chart1.DataBind();
, as the documentation says the chart can bind from a data reader:
http://msdn.microsoft.com/en-us/library/system.web.ui.datavisualization.charting.chart.datasource.aspx
The following is a list of objects that you can use as the data source:
DataView
Data readers (SQL, OleDB)
DataSet
DataTable
[...]
There are other good answers, but since your comment asked how to use a DataTable instead I'll post this anyway. Besides, I don't see how those answers will let you specify the value members, because the code examples I've seen require a named item, and a list of strongs isn't going to do it. (See @Dan's post).
Instead of using a DataReader and using while(reader.Read())
use a DataAdapter to fill the datatable. (Assuming the DB is SQL Server, you'd use a SQLDataAdapter, but there are different DataAdapters.
string connectionstring = "Some connection sting";
string sql = "Select reporttime, datapath from sometable";
System.Data.DataTable t = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter ad = new System.Data.SqlClient.SqlDataAdapter(sql, connectionstring);
ad.Fill(t);
chart1.DataSource = t;
chart1.Series["Series1"].XValueMember = "reporttime";
chart1.Series["Series1"].YValueMembers = "datapath";
List.Add is for one item only. To add multiple items, you would want AddRange:
list.AddRange(new[] { reporttime,datapath,finalconc,DBinstrument } );
However, if you're binding to this, it sounds like you want a list of objects, not strings...so something more like
List<object> list = new List<object>();
while (myReader.Read())
{
reporttime = (string)myReader["reporttime"];
datapath = (string)myReader["datapath"];
list.Add(new {
reporttime = (string)myReader["reporttime"],
datapath = (string)myReader["datapath"]
finalconc = "something",
DBinstrument = "somethingelse?"
});
}
chart1.DataSource = list;
Note, I would suggest in practice creating a business object for this instead of using an anonymous one.
精彩评论