如何将.txt文件放入DataSource?

时间:2011-08-17 16:20:26

标签: c# text datagridview datasource

  

可能重复:
  Putting a .txt file into a DataGridView

当我点击一个打开按钮时,我想选择一个文件并将其放入DataSource以进一步加工成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非常不熟悉,所以如果我可以得到一些帮助,说明它是如何工作的,需要发生什么,看起来怎么样,等等。 :)

感谢。

1 个答案:

答案 0 :(得分:1)

您可以拆分线并循环所有行/列以生成DataTable:

例如(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);
        }
    }
}