这是我解决的程序,它将读取带有分隔符的文本文件,并使用datagridview将数据传输到表。
现在我很难过,因为while循环只是读取所有其他行。
这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
TextReader tr = new StreamReader("aplusixdata.txt");
string[] columns = {"School","Room No.","Student No.","Excercise No.","Problem No.",
"Nth Problem Taken","Date","Time","Excercise Degree",
"Action No.","Duration","Action","Error","Etape",
"Expression","Etat","Cursor Location","Selection",
"Equivalence","Resolution","Empty"};
while (tr.ReadLine() != null)
{
int i = 0;
char[] delimiterChar = { ';' };
string words = tr.ReadLine();
text = words.Split(delimiterChar);
DataRow row = t.NewRow();
foreach (String data in text)
{
//System.Console.WriteLine(data);
System.Console.WriteLine(i);
row[columns[i]] = data;
i++;
}
t.Rows.Add(row);
}
}
答案 0 :(得分:8)
你在每次迭代时都会调用ReadLine
两次 - 一次在这里:
while (tr.ReadLine() != null)
并且在这里:
string words = tr.ReadLine();
将其更改为每次迭代只读一次:
char[] delimiterChar = { ';' };
string words;
while ((words = tr.ReadLine()) != null)
{
int i = 0;
text = words.Split(delimiterChar);
...
}
(请注意,我还将char[]
的创建拉出了循环 - 在每次迭代中都没有必要那个。我个人认为它是一个私有静态变量。)
其他几个风格点:
text
变量在哪里声明?为什么不在循环中声明它呢?我会忽略row
的声明和第一次作业:
DataRow row = t.NewRow();
编辑:根据shahkalpesh的回答,你真的应该使用using
语句来确保你的读者最后关闭。
答案 1 :(得分:3)
这是因为您正在拨打ReadLine
两次电话。
更好的方法是:
while (!tr.EndOfStream)
编辑:最好让代码包围using
子句。
using (TextReader tr = new StreamReader("aplusixdata.txt"))
{
//.. your code here that reads the file line by line
}