2017-04-26 49 views
2

我想將一個.txt文件導入到DataGrid。問題是,雖然代碼工作大部分是確定的,但當導入.txt文件時,它會創建額外的行,如this;當我向其中導入文本文件時,DataGridView會創建額外的行。

 OpenFileDialog ofd = new OpenFileDialog(); 
     ofd.DefaultExt = ".txt"; 
     ofd.InitialDirectory = @"C:\Users\Cabbaa\Desktop"; 
     DialogResult a = ofd.ShowDialog(); 
     var lines = File.ReadAllLines(ofd.FileName); 
     if (lines.Count() > 0) 
     { 
      foreach (var columnName in lines.FirstOrDefault() 
       .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)) 
      { 
       dataGridView1.Rows.Add(Time, Class); 
      } 
      foreach (var cellValues in lines) 
      { 
       var cellArray = cellValues 
        .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); 
       if (cellArray.Length == dataGridView1.Columns.Count) 
        dataGridView1.Rows.Add(cellArray); 
      } 
     } 
+0

你的意思是底部的空行嗎? (我認爲這是「附加一個新記錄行」 DataGrid的。你可以把它們關掉通過設置'dataGrid.AllowUserToAddRows = FALSE') –

+0

哦,不,前兩個人。我想你可以看到他們,如果你檢查我鏈接的imgur文件。 –

+0

啊!我看到他們。不掛斷。 –

回答

0

你的問題在於你的代碼的第一個foreach循環。

 //you are adding rows to the column here, you are not adding headers 
     foreach (
      var columnName in 
      lines.FirstOrDefault().Split(new[] {','}, 
      StringSplitOptions.RemoveEmptyEntries) 
     ) 
     { 
      //since we split the line on commas, 
      //we are adding a row to the table for every 
      //CSV value we found in the current line. 
      //this is causing the "garbage" rows you are seeing 
      //i do not know where "Time" and "Class" come from here. 
      //they weren't part of that first line in this example. 
      //my guess is you do not need this loop at all. 
      //since the headers already neatly show up on the table in your screenshot. 
      dataGridView1.Rows.Add(Time, Class); 
     } 

     //this works just fine. 
     foreach (var cellValues in lines) 
     { 
      var cellArray = cellValues 
       .Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); 
      if (cellArray.Length == dataGridView1.Columns.Count) 
       dataGridView1.Rows.Add(cellArray); 
     } 
+0

我試過了。損壞的前兩行仍然存在。但這一次,它跳過了我的第一行3行。當我將跳過值設置爲0時,則顯示所有3個條目,但前兩個仍保留。 –

+0

我想出了爲什麼發生並更新了答案。 –

+0

非常感謝!解決了這個問題。 –

相關問題