Click here to Skip to main content
15,892,059 members
Articles / Programming Languages / C#
Tip/Trick

Convert DataTable to String by Extension Method

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
28 Sep 2011CPOL 17.7K   5   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Q3 technology
India India
Ram is .Net Architect by profession and passion having 8 year experience. He has extensive experience on Microsoft Development Platform and is also Microsoft Certified Application Developer (MCAD) for Web.
Reach me at rsharma@stackdotnet.com

http://www.stackdotnet.com/
6 Freely avaliable E-Books/

Comments and Discussions

 
GeneralReason for my vote of 5 i USE THIS CODE TO convert datatable... Pin
ShyamSunderVashista2-Oct-11 22:30
professionalShyamSunderVashista2-Oct-11 22:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.