2014-09-22 82 views
0

我是C#的新手。我有一個巨大的文本文件,包含4923行數據,我希望將其添加到DataGridView中。文本文件有很多句子之間的空格和空行。 我希望所有的空白行和空格都被跳過,並將內容加載到DataGriedView。有人給我一個解決方案來實現這一目標。可以在不使用DataTables和Datasource的情況下實現這一目標嗎?如果我的問題是不明確的,請讓我know.There可能是我的失誤code.Please幫我糾正它c#通過跳過空行從文本文件添加4923行到DataGridView

感謝

以下是我的代碼

public void textload() 
    { 
     List<string> str = new List<string>(); 
     String st = ""; 

     //Path to write contents to text file 
     string filename = @"E:\Vivek\contentcopy\clientlist.txt"; 
     Form.CheckForIllegalCrossThreadCalls = false; 
     OpenFileDialog ofd = new OpenFileDialog(); 
     ofd.FileName = ""; 
     ofd.Filter = "csv files|*.csv|txt files|*.txt|All Files|*.*"; 
     ofd.ShowDialog(); 
     st = ofd.FileName; 

     if (string.IsNullOrEmpty(ofd.FileName)) 
      return; 

     string[] lines = File.ReadAllLines(st); 
     for (int i = 0; i < lines.Length; i++) 
     { 

      listBox1.Items.Add(lines[i]); 
      string[] s = lines[i].Split(' '); 
      MessageBox.Show(s.Length.ToString()); 
      str.Add(lines[i]); 
      dataGridView1.Rows.Add(); 
      if (s[i] == null && s[i] == " ") 
      { 
        continue; 
      }   



        dataGridView1.Rows[i].Cells[i].Value=s[i]; 
        //dataGridView1.Rows[i].Cells[10].Value = s[10]; 
        //dataGridView1.Rows[i].Cells[11].Value = s[11]; 
        //dataGridView1.Rows[i].Cells[12].Value = s[12]; 
        //dataGridView1.Rows[i].Cells[13].Value = s[13]; 
        //dataGridView1.Rows[i].Cells[14].Value = s[14]; 
        //dataGridView1.Rows[i].Cells[15].Value = s[15]; 


      } 


      File.WriteAllLines(filename, str); 
      dataGridView1.ReadOnly = true; 

}

+1

嘗試'.Replace('','')。ToString()' – 2014-09-22 04:39:01

+0

@LeoSarmiento在哪裏添加上面的行先生? – user2614235 2014-09-22 04:47:00

+0

您可以向我們展示您想要解析的示例文本嗎? 「IndexOutOfBoundException」與「OutOfMemoryException」不同。網格中和文本文件中的列數不匹配。 – NeverHopeless 2014-09-23 05:57:47

回答

1

一選項是在讀完它時立即過濾出空字符串。這可以使用LINQ Where以及傳遞條件來檢查字符串是否僅爲空白。 String.IsNullOrWhitepspace涵蓋(此外,它將檢查null,在使用ReadAllLines的情況下不會發生)。

string[] lines = File.ReadAllLines(st) 
    .Where(s => !String.IsNullOrWhitespace(s)) 
    .ToArray(); 
+0

感謝@ALexie,現在我已經過濾了所有空字符串,如何將內容加載到DataGridView? – user2614235 2014-09-22 04:46:39

+1

@ user2614235,只是旁註:。如果文件非常大,如果一次加載完整內容,則可能會發生「OutOfMemoryException」。 – NeverHopeless 2014-09-22 06:12:33

+0

@NeverHopeless你說得對。我在dataGridView1.Rows [i] .Cells [i] .Value = lines [i]獲得IndexOutOfBound異常。請問如何將數據加載到DataGridview – user2614235 2014-09-22 06:27:11

相關問題