2014-03-06 54 views
0

我有一個代碼,打開點文件和讀取數據文件:加載的.txt數據文件的DataGridView

private void cmdload_Click(object sender, EventArgs e) 
{ 
    Stream myStream = null; 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

    openFileDialog1.InitialDirectory = "\\Yamaha"; 
    openFileDialog1.FilterIndex = 2; 
    openFileDialog1.RestoreDirectory = true; 

    if (openFileDialog1.ShowDialog() == DialogResult.OK) 
    { 
     try 
     { 
      if ((myStream = openFileDialog1.OpenFile()) != null) 
      { 
       using (myStream) 
       { 
        string filename = openFileDialog1.FileName; 
        using (var reader = File.OpenText(@filename)) 
        { 
         string line; 
         while ((line = reader.ReadLine()) != null) 
         { 
          //Do fetch data and paste to gridview operation 
         } 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
     } 
    } 
} 

現在我被困在while循環。我希望循環遍歷文件並獲取所有數據並將其粘貼到gridview上。

我的GridView是這樣的:

我的文本文件是這樣的:

+0

我看到你的文本文件中的每個值之間固定的空間,所以你需要先提取文件一行一行地(中環),然後使用字符串函數(例如,你可以用一個減號repalce固定空格: - 然後在負號上分割每一行以獲取單個值作爲簡單的字符串數組元素,然後創建一個GridViewRow對象設置單元格等等。您需要付出更多的努力來完成,因爲根據問題提供的代碼處於非常初始級別 –

+0

你知道'string [] System.IO.File.ReadAllLines(string path)''方法''參見[MSDN](http://msdn.microsoft.com/de-de/library/system.io.file.readalllines% 28v = vs.110%29.aspx) – helb

+0

通常情況下,您不會將數據粘貼到datagridview,但您將其設置爲DataSource屬性。 – VahidNaderi

回答

1

如果你的文件是沒有那麼大,這將是使用LINQ非常簡單。你只需要讀取所有行解析每一行並設置GridView的數據源。

private void cmdload_Click(object sender, EventArgs e) 
{ 
    OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

    openFileDialog1.InitialDirectory = "\\Yamaha"; 
    openFileDialog1.FilterIndex = 2; 
    openFileDialog1.RestoreDirectory = true; 

    if (openFileDialog1.ShowDialog() == DialogResult.OK) 
    { 
     try 
     { 
      string[] fileLines= System.IO.File.ReadAllLines(openFileDialog1.FileName); 
      IEnumerable<string[]> splitedLines = fileLines.Select(c => c.Split(new string[]{" "}, StringSplitOptions.RemoveEmptyEntries)); 
      var data = splitedLines.Select(c => new 
      { 
       Point = c[0], 
       X = c[2],//c[1] would be "=" sign 
       Y = c[3], 
       Z = c[4], 
       R = c[5], 
       A = c[6], 
       B = c[7], 
       C = c[8] 
      }); 
      dataGridView1.DataSource = data.ToArray(); 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show("Error: Something is not right. Original error: " + ex.Message); 
     } 
    } 
} 
+0

但此程序無關與數據庫。所以不需要數據源?請指教。 – Ren

+0

DataSource不只是關於數據庫,這個屬性獲取或設置DataGridView顯示數據的數據源,並且可以從任何類型的數據源,數據庫,純文本文件,xml和...讀取數據。 – VahidNaderi

+0

Tq的建議,但我嘗試這個代碼,仍然沒有工作..沒有錯誤,但沒有發生..任何想法? – Ren