1

I have a string something like this:

"X","Y","Z"
"X2","Y2","Z2"

i.e, Multiple rows seperated by a new line containing multiple different string values delimited by commas.

How could I create a function to input these values into a datatable like this:

"X" "Y" "Z"
"X2" "Y2" "Z2"

for any number of rows and columns in my string?

Here's what I have so far:

public static DataTable writeToDT(string data) //Write to datatable from string
    {
        DataTable dataTable = new DataTable();
        foreach (string header in csvHeader)
        {
            dataTable.Columns.Add(header);
        }
        using (StringReader reader = new StringReader(data))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                DataRow dataRow = dataTable.NewRow();
            }
        }
        return dataTable;
    }

Where csvheader is an array already filled with the headers in my data.
I believe this creates an empty datatable with the right amount of rows and columns, but I'm not sure how to fill it with the string data I have.

Thanks in advance.

ToppuKekku
  • 13
  • 1
  • 3

1 Answers1

1

Something like this should work. Parsing CSV is a solved problem, the TextFieldParser class in the using Microsoft.VisualBasic.FileIO; namespace (add a reference to Microsoft.VisualBasic) can do this for you.

public static DataTable WriteToDataTable(string data)
{
    DataTable dataTable = new DataTable();
    foreach (var header in csvHeader)
        dataTable.Columns.Add(header);

    using (var reader = new StringReader(data))
    {
        TextFieldParser csvParser = new TextFieldParser(reader) { HasFieldsEnclosedInQuotes = true, Delimiters = new string[] { "," } };

        while (!csvParser.EndOfData)
        {
            var dataTableRow = dataTable.NewRow();
            dataTableRow.ItemArray = csvParser.ReadFields();
            dataTable.Rows.Add(dataTableRow);
        }
    }
    return dataTable;
}
steve16351
  • 5,372
  • 2
  • 16
  • 29
  • 1
    Perfect, thanks! If anyone else has this problem note that I had to enable Microsoft.VisualBasic.FileIO under PROJECT > Add Reference > Assemblies > Framework. – ToppuKekku Jan 31 '15 at 18:53