SPLIT STRING BY # AND STORE RESULT IN A DATATABLE

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
C#  String  Split 
 988  View(s)
Ratings:
Rate this:

I have this string:

1#3.doc#0.036/n

2#1.doc#0.026/n

I want to split it on # and put every line in a single row inside DataTable like this:

1    3.doc  0.036

2    1.doc  0.026

I have a DataTable like this:

DataTable table = new DataTable();

table.Columns.Add("Id", typeof(int));

table.Columns.Add("FileName", typeof(string));

table.Columns.Add("Content", typeof(string));

How can I do that?

  1. Simons Hood

    Post:70

    Points:494
    Re: Split string by # and store result in a datatable

    Here is how you would split a string into lines, and then those lines into different parts.

    Your string is first split by the new line character \n into an array of lines string[].

    Then those lines, one by one, are split into parts by Split('#').

    And finally those parts are added to your table with the columns you created.

    Remember to save the columns you created and don't forget to add the newly created row to the table.

    DataTable table = new DataTable();

    DataColumn colID = table.Columns.Add("Id", typeof(int));

    DataColumn colFileName = table.Columns.Add("FileName", typeof(string));

    DataColumn colContent = table.Columns.Add("Content", typeof(string));

    string source = "1#3.doc#0.036\n2#1.doc#0.026\n";

    string[] lines = source.Split('\n');

    foreach(var line in lines)

    {

        string[] split = line.Split('#');

        DataRow row = table.NewRow();

        row.SetField(colID, int.Parse(split[0]));

        row.SetField(colFileName, split[1]);

        row.SetField(colContent, split[2]);

        table.Rows.Add(row);

    }

    Adding data to the row with row["FileName"] = data is also possible, but this will break if you change the name of your column, while references to the column objects are checked by the compiler and your IDE. Also this article explains how to create a typed DataTable, which is something you may want to do.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!