ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET Hosting - ASPHostPortal.com :: Convert DataTable To JSON String in ASP.NET

clock August 16, 2016 19:56 by author Armend

In this post we will explain about how to Convert DataTable To JSON String in ASP.NET . 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:

Convert DataTable To JSON String.       
    using System.Data 
    using System.Text; 
    public class ConvertDatatableToJson 
    { 
       public string DataTableToJson(DataTable dt) 
       { 
          DataSet ds = new DataSet(); 
          ds.Merge(dt); 
          StringBuilder JsonStr = new StringBuilder(); 
          if (ds != null && ds.Tables[0].Rows.Count > 0) 
          { 
             JsonStr.Append("["); 
             for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
             { 
                JsonStr.Append("{"); 
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++) 
                { 
                   if (j < ds.Tables[0].Columns.Count - 1) 
                   { 
                      JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\","); 
                   } 
                   else if (j == ds.Tables[0].Columns.Count - 1) 
                   { 
                      JsonStr.Append("\"" + ds.Tables[0].Columns[j].ColumnName.ToString() + "\":" + "\"" + ds.Tables[0].Rows[i][j].ToString() + "\""); 
                   } 
                } 
                if (i == ds.Tables[0].Rows.Count - 1) 
                { 
                   JsonStr.Append("}"); 
                } 
                else    
                { 
                   JsonStr.Append("},"); 
                } 
             } 
             JsonStr.Append("]"); 
             return JsonStr.ToString(); 
          } 
          else 
          { 
             return null; 
          } 
       }

Step 2

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

<asp:GridView ID="ui_grdVw_EmployeeDetail" runat="server" Width="50%" AutoGenerateColumns="false" HeaderStyle-CssClass="pageheading"> 
    <Columns> 
    <asp:TemplateField HeaderText="S.NO"> 
    <ItemTemplate> 
    <%#Container.DataItemIndex+1 %> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee ID"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmployeeID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_id") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee Name"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmployeeName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Name") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Employee Post"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_EmpJob" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_job") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    <asp:TemplateField HeaderText="Department"> 
    <ItemTemplate> 
    <asp:Label ID="ui_lbl_Department" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Emp_Dep") %>'></asp:Label> 
    </ItemTemplate> 
    </asp:TemplateField> 
    </Columns> 
    </asp:GridView> 
    <br /> 
    <asp:Button ID="ui_btn_Convert1" runat="server" Text="Manually Convert To Json" OnClick="ui_btn_Convert1_Click" /><br /><br /><br /> 
    <asp:Label ID="ui_lbl_JsonString1" runat="server"></asp:Label>

Step 3

Now, open the Deafult.asps.cs then write the following code:
    using System; 
    using System.Data;
 

    public partial class _Default : System.Web.UI.Page 
    { 
       #region Global Variable 
       DataTable dt; 
       ConvertDatatableToJson dtJ; 
       string JsonString = string.Empty;    
       #endregion 
        
       protected void Page_Load(object sender, EventArgs e) 
       { 
          if (!IsPostBack) 
          { 
             ui_grdvw_EmployeeDetail_Bind(); 
          } 
       }       
       protected void ui_grdvw_EmployeeDetail_Bind() 
       { 
          dt = new DataTable(); 
          EmployeeRecord employeeRecord = new EmployeeRecord(); 
          dt = employeeRecord.EmpRecord(); 
          ViewState["dt"] = dt; 
          ui_grdVw_EmployeeDetail.DataSource = dt; 
          ui_grdVw_EmployeeDetail.DataBind(); 
       }       
       protected void ui_btn_Convert1_Click(object sender, EventArgs e) 
       { 
          dtJ = new ConvertDatatableToJson(); 
          JsonString = dtJ.DataTableToJson((DataTable)ViewState["dt"]); 
          ui_lbl_JsonString1.Text = JsonString; 
       } 
    }

Step 4

Press F5, run the project.

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:

<asp:Button ID="iu_btn_Convert2" runat="server" Text="Newtonsoft Convert To Json" OnClick="iu_btn_Convert2_Click" /> 
    <br /> 
    <br /> 
    <asp:Label ID="ui_lbl_JsonString2" runat="server"></asp:Label>

Step 3

Now, write the following code in Default.aspx.cs:
using this namespace

using Newtonsoft.Json;

And then:

protected void iu_btn_Convert2_Click(object sender, EventArgs e) 
    { 
       dt = (DataTable)ViewState["dt"]; 
       JsonString = JsonConvert.SerializeObject((DataTable)ViewState["dt"]); 
       ui_lbl_JsonString2.Text = JsonString; 
    }

Now, run the project and click on the Newtonsoft Convert to JSON     

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.   

 



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in