none
Loading a datatable from a CSV file with uneven column numbers per row

    Pregunta

  • Hi,  I am trying to load a datatable from a CSV file with non-standard columns.  I have tried the below code.  I am able to see the data in the row string when I pause the app but it never loads in the dt Datatable...

    Thanks!

        class CSVParser
        {
            public DataTable FullDT(string csvfile)
            {
                string lines = null;
                DataTable dt = new DataTable();
                StreamReader read = new StreamReader(csvfile);
                for (int i = 0; i < 95; i++)
                {
                    dt.Columns.Add();
                }
                while ((lines = read.ReadLine()) != null)
                {
                    string[] row = lines.Split(',');
                    dt.NewRow();
                    dt.Rows.Add(row);
                }
                return dt;
            }
        }
    

    domingo, 15 de abril de 2012 21:04

Respuestas

  • I think what you probably meant to do is this:

    public DataTable FullDT(string csvfile)
    {
        string lines = null;
        DataTable dt = new DataTable();
        StreamReader read = new StreamReader(csvfile);
        for (int i = 0; i < 95; i++)
        {
            dt.Columns.Add();
        }
        DataRow dataRow;
        while ((lines = read.ReadLine()) != null)
        {
            string[] row = lines.Split(',');
            dataRow = dt.NewRow();
            for (int i=0; i < row.Length, i++)
            {
                dataRow[i] = row;
            }
            dt.Rows.Add(dataRow);
        }
        return dt;
    }


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    • Marcado como respuesta TonyL1234 martes, 17 de abril de 2012 14:41
    lunes, 16 de abril de 2012 1:02

Todas las respuestas