0

So far I have tried to convert DataTable to String as follow:-

public static string convertDataTableToString(DataTable dataTable)
    {
        string data = string.Empty;
        int rowsCount = dataTable.Rows.Count;
        for (int i = 0; i < rowsCount; i++)
        {
            DataRow row = dataTable.Rows[i];
            int columnsCount = dataTable.Columns.Count;
            for (int j = 0; j < columnsCount; j++)
            {
                data += dataTable.Columns[j].ColumnName + "~" + row[j];
                if (j == columnsCount - 1)
                {
                    if (i != (rowsCount - 1))
                        data += "$";
                }
                else
                    data += "|";
            }
        }
        return data;
    }

Now I want to convert returned string into DataTable again.

7
  • 4
    Classic but, did you tried anything? Commented Mar 6, 2014 at 14:59
  • 2
    Why not use XML? DataTable already has conversion methods to/from XML. Commented Mar 6, 2014 at 15:01
  • @D Stanley I have to encrypt string and than decrpty it in other application and convert it into data table Commented Mar 6, 2014 at 15:04
  • @Soner Gönül I am trying but always getting different results. Commented Mar 6, 2014 at 15:05
  • Comment for Down Vote please ? Commented Mar 6, 2014 at 15:12

1 Answer 1

3

You can use String.Split to break your string into rows and cells. If the column setup is always the same (as it should be), then you can simply add the columns on your first iteration through the cells.

Here's a simple example:

public static DataTable convertStringToDataTable(string data)
{
    DataTable dataTable = new DataTable();
    bool columnsAdded = false;
    foreach(string row in data.Split('$'))
    {
        DataRow dataRow = dataTable.NewRow();
        foreach(string cell in row.Split('|'))
        {
            string[] keyValue = cell.Split('~');
            if (!columnsAdded)
            {
                DataColumn dataColumn = new DataColumn(keyValue[0]);
                dataTable.Columns.Add(dataColumn);
            }
            dataRow[keyValue[0]] = keyValue[1];
        }
        columnsAdded = true;
        dataTable.Rows.Add(dataRow);
    }
    return dataTable;
}

Alternatively you could get a list of all columns prior to the loop, but this way is likely easier for your purpose.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.