Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Convert DataTable to String by Extension Method

0.00/5 (No votes)
28 Sep 2011 1  
Useful when calling a C# method from JavaScript by using JSON which returns a DataTable.

This article is useful when a user wants to call a C# method from JavaScript which returns a datatable, and then you need to convert the datatable to string.


C#
public static string ConvertDataTableToString(this DataTable dt)
{
    StringBuilder JsonString = new StringBuilder();

    //Exception Handling        
    if (dt != null && dt.Rows.Count > 0)
    {
        JsonString.Append("{ ");
        JsonString.Append("\"Head\":[ ");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            JsonString.Append("{ ");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (j < dt.Columns.Count - 1)
                {
                    JsonString.Append("\"" + 
                      dt.Columns[j].ColumnName.ToString().Trim() + "\":" + 
                      "\"" + dt.Rows[i][j].ToString().Trim() + "\",");
                }
                else if (j == dt.Columns.Count - 1)
                {
                    //string cleaned = original.Replace(@"\""", "");
                    JsonString.Append("\"" + 
                      dt.Columns[j].ColumnName.ToString().Trim() + 
                      "\":" + "\"" + 
                      dt.Rows[i][j].ToString().Trim().CleanInput() + "\"");
                }
            }
            /*end Of String*/
            if (i == dt.Rows.Count - 1)
            {
                JsonString.Append("} ");
            }
            else
            {
                JsonString.Append("}, ");
            }
        }
        JsonString.Append("]}");
        return JsonString.ToString();
    }
    else
    {
        return null;
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here