Convert DataTable To JSON String in ASP.Net

Here I will explain how to convert a DataTable to JSON string using a written helper function (in C#) and Newtonsoft DLL.

First of all you need to create an "ASP.NET Empty Web Site". Then use the following procedure.

Step 1

Create a ConvertDataTableToJson class in the App_Code folder and provide the following:

  1. Convert DataTable To JSON String.  
  2.   
  3. using System.Data  
  4. using System.Text;  
  5. public class ConvertDatatableToJson  
  6. {  
  7.    public string DataTableToJson(DataTable dt)  
  8.    {  
  9.       DataSet ds = new DataSet();  
  10.       ds.Merge(dt);  
  11.       StringBuilder JsonStr = new StringBuilder();  
  12.       if (ds != null && ds.Tables[0].Rows.Count > 0)  
  13.       {  
  14.          JsonStr.Append("[");  
  15.          for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
  16.          {  
  17.             JsonStr.Append("{");  
  18.             for (int j = 0; j < ds.Tables[0].Columns.Count; j++)  
  19.             {  
  20.                if (j < ds.Tables[0].Columns.Count - 1)  
  21.                {  
  22.                   JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\",");  
  23.                }  
  24.                else if (j == ds.Tables[0].Columns.Count - 1)  
  25.                {  
  26.                   JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\"");  
  27.                }  
  28.             }  
  29.             if (i == ds.Tables[0].Rows.Count - 1)  
  30.             {  
  31.                JsonStr.Append("}");  
  32.             }  
  33.             else     
  34.             {  
  35.                JsonStr.Append("},");  
  36.             }  
  37.          }  
  38.          JsonStr.Append("]");  
  39.          return JsonStr.ToString();  
  40.       }  
  41.       else  
  42.       {  
  43.          return null;  
  44.       }  
  45.    }  
Step 2

Insert the grid view control into the Default.aspx page then write the following design code:

  1. <asp:GridView ID="ui_grdVw_EmployeeDetail" runat="server" Width="50%" AutoGenerateColumns="false" HeaderStyle-CssClass="pageheading">  
  2. <Columns>  
  3. <asp:TemplateField HeaderText="S.NO">  
  4. <ItemTemplate>  
  5. <%#Container.DataItemIndex+1 %>  
  6. </ItemTemplate>  
  7. </asp:TemplateField>  
  8. <asp:TemplateField HeaderText="Employee ID">  
  9. <ItemTemplate>  
  10. <asp:Label ID="ui_lbl_EmployeeID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_id") %>'></asp:Label>  
  11. </ItemTemplate>  
  12. </asp:TemplateField>  
  13. <asp:TemplateField HeaderText="Employee Name">  
  14. <ItemTemplate>  
  15. <asp:Label ID="ui_lbl_EmployeeName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Name") %>'></asp:Label>  
  16. </ItemTemplate>  
  17. </asp:TemplateField>  
  18. <asp:TemplateField HeaderText="Employee Post">  
  19. <ItemTemplate>  
  20. <asp:Label ID="ui_lbl_EmpJob" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_job") %>'></asp:Label>  
  21. </ItemTemplate>  
  22. </asp:TemplateField>  
  23. <asp:TemplateField HeaderText="Department">  
  24. <ItemTemplate>  
  25. <asp:Label ID="ui_lbl_Department" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Dep") %>'></asp:Label>  
  26. </ItemTemplate>  
  27. </asp:TemplateField>  
  28. </Columns>  
  29. </asp:GridView>  
  30. <br />  
  31. <asp:Button ID="ui_btn_Convert1" runat="server" Text="Manually Convert To Json" OnClick="ui_btn_Convert1_Click" /><br /><br /><br />  
  32. <asp:Label ID="ui_lbl_JsonString1" runat="server"></asp:Label>  
Step 3

Now, open the Deafult.asps.cs then write the following code:

  1. using System;  
  2. using System.Data;  
  3.   
  4. public partial class _Default : System.Web.UI.Page  
  5. {  
  6.    #region Global Variable  
  7.    DataTable dt;  
  8.    ConvertDatatableToJson dtJ;  
  9.    string JsonString = string.Empty;     
  10.    #endregion  
  11.      
  12.    protected void Page_Load(object sender, EventArgs e)  
  13.    {  
  14.       if (!IsPostBack)  
  15.       {  
  16.          ui_grdvw_EmployeeDetail_Bind();  
  17.       }  
  18.    }  
  19.   
  20.    protected void ui_grdvw_EmployeeDetail_Bind()  
  21.    {  
  22.       dt = new DataTable();  
  23.       EmployeeRecord employeeRecord = new EmployeeRecord();  
  24.       dt = employeeRecord.EmpRecord();  
  25.       ViewState["dt"] = dt;  
  26.       ui_grdVw_EmployeeDetail.DataSource = dt;  
  27.       ui_grdVw_EmployeeDetail.DataBind();  
  28.    }  
  29.   
  30.    protected void ui_btn_Convert1_Click(object sender, EventArgs e)  
  31.    {  
  32.       dtJ = new ConvertDatatableToJson();  
  33.       JsonString = dtJ.DataTableToJson((DataTable)ViewState["dt"]);  
  34.       ui_lbl_JsonString1.Text = JsonString;  
  35.    }  
  36. }  

Step 4

Press F5, run the project.

default page

Now, convert the DataTable to a JSON string using the newtonsoft DLL.

Step 1

Download the Newtonsoft DLL and move it to the ASP.Net project's bin folder.

Step 2
 
Then, insert a button and label UI Control in the Deafult.aspx page as in the following:
  1. <asp:Button ID="iu_btn_Convert2" runat="server" Text="Newtonsoft Convert To Json" OnClick="iu_btn_Convert2_Click" />  
  2. <br />  
  3. <br />  
  4. <asp:Label ID="ui_lbl_JsonString2" runat="server"></asp:Label>  
Step 3
 
Now, write the following code in Default.aspx.cs:

using this namespace.
  1. using Newtonsoft.Json;   
And then:
  1. protected void iu_btn_Convert2_Click(object sender, EventArgs e)  
  2. {  
  3.    dt = (DataTable)ViewState["dt"];  
  4.    JsonString = JsonConvert.SerializeObject((DataTable)ViewState["dt"]);  
  5.    ui_lbl_JsonString2.Text = JsonString;  
  6. }  
Now, run the project and click on the Newtonsoft Convert to JSON.

converted json

In the preceding code, I convert the DataTable to a JSON String.

I have attached the sample project for this, download and see how it works.

Thank you.