Thursday, January 5, 2012

How convert datatable to string in 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;
    }
}
                                         


    private static String CleanInput(this string strIn)
        {
            // Replace invalid characters with empty strings.
            return Regex.Replace(strIn, @"[^\w\.@-]"" ");
        }