当前位置: 动力学知识库 > 问答 > 编程问答 >

How to Convert String Data to Data Table in C# asp.net?

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: