C# Windows 表单图表控件 - 从 csv 文件绑定多个 y 值

C# Windows Form Chart control - binding multiple y values from csv file

这是我第一次接触数据绑定,所以我对涉及的所有属性和方法知之甚少。我想将多个系列绑定到一个 csv 文件,其中第 1 列是日期时间,第 2 列到第 N 列是双精度数。我从 WinFormsChartSamples 中的示例开始,将单个 Y 值绑定到 csv;但是,不要相信我正在理解绑定多个 Y 值的方法。

原代码:

string mySelectQuery = "Select * from " + file;
string ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
path + ";Extended Properties=\"Text;HDR=No;FMT=Delimited\"";

OleDbConnection myConnection = new OleDbConnection(ConStr);

// create a database command on the connection using query
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);

// open the connection
myCommand.Connection.Open();

// create a database reader
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

// column 1 is a time value, column 2 is a double
// databind the reader to the chart using the DataBindXY method
chart1.Series[0].Points.DataBindXY(myReader, "1", myReader, "2");

以下作品:

myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
chart1.Series[0].Points.DataBindXY(myReader, "1", myReader, "2");

myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
chart1.Series[1].Points.DataBindXY(myReader, "1", myReader, "3");

myCommand.Connection.Open();
myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
chart1.Series[2].Points.DataBindXY(myReader, "1", myReader, "4");

我可以将以上内容放入循环中并遍历所有系列,但肯定有比多次读取 csv 文件更好的方法吗?

原来我确实找到了更好的方法:

string mySelectQuery = "Select * from " + file;
string ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path +
";Extended Properties=\"Text;HDR=No;FMT=Delimited\"";

OleDbConnection myConnection = new OleDbConnection(ConStr);
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);

chart1.DataSource = myCommand;

for (int i = 0; i < chart1.Series.Count; i++) {
    chart1.Series[i].XValueMember = "1";
    chart1.Series[i].YValueMembers = (i+2).ToString();
}
chart1.DataBind(); 

也许这会对其他人有所帮助...