2011-08-17 18 views
0

可能重複:
Putting a .txt file into a DataGridView如何將.txt文件放入數據源?

當我單擊打開按鈕,我想選擇一個文件,把它變成一個DataSource到futher被加工成DataGridView

現在我有什麼看起來像這樣:

OpenFileDialog openFile = new OpenFileDialog(); 

openFile.DefaultExt = "*.txt"; 
openFile.Filter = ".txt Files|*.txt"; 
openFile.RestoreDirectory = true; 

try 
{ 
    if (openFile.ShowDialog() == DialogResult.OK && openFile.FileName.Length > 0) 
    { 
     // Right now I am loading the file into a RichTextBox 
     openFileRTB.LoadFile(openFile.FileName, RichTextBoxStreamType.PlainText); 

     // What I would like to do is load it into a DataSource and then into a DataGridView. 
     // So really I would like to remove the openFileRTB line of code and replace it. 
     // That is where I need help :). 
    } 
} 

catch (Exception) 
{ 
    MessageBox.Show("There was not a specified file path to open.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
} 

這裏有一個文件,我將打開(空格分隔)的例子:

Title1 Title2 Title3 Title4 Title5 Title6 
abc123 abc123-123-123 225.123 123.456 180 thing99 
c123 somethingHERE 987.123 123.456 360 anotherThing1 
abc124 somethingHERE225.123 123.456 0 thing99 

我很熟悉DataSourceDataGridView所以如果我能得到一些幫助它如何工作,需要發生什麼,它將如何看,等將不勝感激。 :)

謝謝。

+0

_「into a DataSource」_?你究竟是什麼意思? – stakx

+0

@Stakx:那麼我想使用IBindingSource,這樣我就可以從txt文件填充DataGridView – theNoobGuy

+0

@theNoobGuy,'IBindingSource'不是一個容器。你不能把任何東西「放入」它。相反,它具有必須設置的自己的'DataSource'屬性(意思是說:你的數據必須放在別的地方,例如放到'DataTable'中 - 參見鏈接的問題)。所以'IBindingSource'不是數據源,但更類似於另一個數據源的適配器或裝飾器。 – stakx

回答

1

你可以分割線和迴路中的所有行/列生成數據表:

例如(VB.NET):

Dim separator = " "c 
Dim fileName = OpenFileDialog1.FileName 
Dim tbl As New DataTable(fileName) 
Dim query = From line In IO.File.ReadAllLines(fileName) 
      Let row = line.Split(separator) 

If query.Any Then 
    For Each col In query(0).row 
     'build DataColumns from first line' 
     tbl.Columns.Add(New DataColumn(col)) 
    Next 
    If query.Count > 1 Then 
     For rowIndex = 1 To query.Count - 1 
      Dim newRow = tbl.NewRow 
      For colIndex = 0 To query(rowIndex).row.Length - 1 
       Dim colValue = query(rowIndex).row(colIndex) 
       newRow(colIndex) = colValue 
      Next 
      tbl.Rows.Add(newRow) 
     Next 
    End If 
End If 

該作品一樣好沒有LINQ(現在還在C#;)):

.... 
var rows = System.IO.File.ReadAllLines(fileName); 
if (rows.Length != 0) { 
    foreach (string headerCol in rows(0).Split(separator)) { 
     tbl.Columns.Add(new DataColumn(headerCol)); 
    } 
    if (rows.Length > 1) { 
     for (rowIndex = 1; rowIndex < rows.Length; rowIndex++) { 
      var newRow = tbl.NewRow(); 
      var cols = rows(rowIndex).Split(separator); 
      for (colIndex = 0; colIndex < cols.Length; colIndex++) { 
       newRow(colIndex) = cols(colIndex); 
      } 
      tbl.Rows.Add(newRow); 
     } 
    } 
} 
+0

謝謝,有點幫助..不太熟悉VB.net雖然哈哈 – theNoobGuy

+0

@theNoobGuy:我最近編輯了我的答案,並提供了一個C#示例。 –

+0

'回合(-0.49)'回答重複的問題。 ;) – stakx

相關問題