当您使用Multiselect 时,您必须遍历用户选择的所有文件,而不是使用OpenFile() 方法,因为它仅适用于一个文件
if (ff.ShowDialog() == DialogResult.OK)
{
//if ((myStream = ff.OpenFile()) != null)
foreach (String file in ff.FileNames)
{
myStream = File.OpenRead(file);
// ...
}
}
编辑:关于其他需要修改的代码部分:
你必须使用rrList 作为List<Read> 而不是一个rr。
GraphDemo.cs:
Read rr;
List<Read> rrList = new List<Read>(); // *** new
void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog ff = new OpenFileDialog();
ff.InitialDirectory = "C:\\";
ff.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*";
ff.Multiselect = true;
ff.FilterIndex = 1;
ff.RestoreDirectory = true;
if (ff.ShowDialog() == DialogResult.OK)
{
try
{
rrList.Clear(); //***
foreach (String file in ff.FileNames) //if ((myStream = ff.OpenFile()) != null)
{
using (myStream = File.OpenRead(file))
{
rr = new Read(myStream);
rr.fileName = Path.GetFileName(file); // !!! new
string[] header = rr.get_Header();
List<string> lX = new List<string>();
List<string> lY = new List<string>();
for (int i = 0; i < header.Length; i++)
{
lX.Add(header[i]); lY.Add(header[i]);
}
//Populate the ComboBoxes
xBox.DataSource = lX;
yBox.DataSource = lY;
// Close the stream
myStream.Close();
}
rrList.Add(rr); //***
}
}
catch (Exception err)
{
//Inform the user if we can't read the file
MessageBox.Show(err.Message);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Plot p = new Plot(rrList, xBox, yBox, chart); //*** use rrList instead of rr
}
和绘图类:
class Plot
{
public Plot(List<Read> rrList, ComboBox xBox, ComboBox yBox, Chart chart) //***
{
int indX = xBox.SelectedIndex;
int indY = yBox.SelectedIndex;
chart.Series.Clear(); //ensure that the chart is empty
chart.Legends.Clear();
Legend myLegend = chart.Legends.Add("myLegend"); // !!! new
myLegend.Title = "myTitle"; // !!! new
int i = 0; //series index
foreach (Read rr in rrList)
{
float[,] data = rr.get_Data();
int nLines = rr.get_nLines();
int nColumns = rr.get_nColumns();
string[] header = rr.get_Header();
chart.Series.Add("Series" + i);
chart.Series[i].ChartType = SeriesChartType.Line;
chart.Series[i].LegendText = rr.fileName; // !!! new
chart.ChartAreas[0].AxisX.LabelStyle.Format = "{F2}";
chart.ChartAreas[0].AxisX.Title = header[indX];
chart.ChartAreas[0].AxisY.Title = header[indY];
for (int j = 0; j < nLines; j++)
{
chart.Series[i].Points.AddXY(data[j, indX], data[j, indY]);
}
i++; //series index
}
}
}
添加到Read 类:
public string fileName { get; set; } // !!! new
注意:您的代码方法不太好,例如 Plot 应该是其类中的 void 方法,而不是构造函数,因为您每次要绘制新的 Plot 实例时都必须重新创建一个新实例不需要的情节。那里还有很多其他的技巧......但它的工作原理