locked
Tabel from text files RRS feed

  • Question

  • is there a way to get c# to load all of the text in a floder in a tabel

    Below is how i would like it set out

    Frist Name

    Last Name

    Age

    Frist Line from first text file

    Second line from first text file

    Third line from first text file

    Frist Line from second text file

    Second line from second text file

    Third line from second text file

    i would want to load any new text file i add at at a later date by it self and what i had it mind for would be use more columns





    • Edited by philip_95 Monday, July 15, 2013 10:13 AM fix tabel
    Monday, July 15, 2013 10:05 AM

Answers

  • Yes, but you won't find a Form_Load event. You can take the 'Window_Loaded' event, instead.

    And you can replace the line

    dataGridView1.DataSource = dt.DefaultView;

    with

    dataGrid1.ItemsSource = dt.DefaultView;

    , if you wish to use a DataGrid control (that comes close to the DataGridView of Windows Forms).

    • Marked as answer by Bob Shen Friday, July 26, 2013 7:17 AM
    Monday, July 15, 2013 1:43 PM

All replies

  • If you know the number of your columns in advance, it is quite simple to read those lines into a table (e.g. a DataTable). Your text files need to have a number of lines corresponding to the number of columns. Try the following:

    public Form1() {
        InitializeComponent();
        dt.Columns.Add(new DataColumn("First Name"));
        dt.Columns.Add(new DataColumn("Last Name"));
        dt.Columns.Add(new DataColumn("Age"));
    }
    
    private void Form1_Load(object sender, EventArgs e) {
        string[] fArr = Directory.GetFiles(path, "*.txt");
        foreach (var item in fArr) {
            DataRow row = dt.NewRow();
            int cnt = 0;
            foreach (var line in File.ReadLines(item)) {
                row[cnt] = line;
                cnt++;
            }
            dt.Rows.Add(row);
        }
        dataGridView1.DataSource = dt.DefaultView;
    }
    
    wizend

    • Proposed as answer by mkruluts Monday, July 15, 2013 12:38 PM
    Monday, July 15, 2013 12:06 PM
  • thanks will this work in a WPF app?
    Monday, July 15, 2013 12:12 PM
  • Yes, but you won't find a Form_Load event. You can take the 'Window_Loaded' event, instead.

    And you can replace the line

    dataGridView1.DataSource = dt.DefaultView;

    with

    dataGrid1.ItemsSource = dt.DefaultView;

    , if you wish to use a DataGrid control (that comes close to the DataGridView of Windows Forms).

    • Marked as answer by Bob Shen Friday, July 26, 2013 7:17 AM
    Monday, July 15, 2013 1:43 PM