connectseekers.com

Tuesday, 28 June 2016

Convert DataTable To JSON Object/Data In ASp.Net Using C#.Net

6/28/2016 - By Pranav Singh 0

This article will show you how you can convert the datatable values into the JSON data in asp.net using c#.Net and display it into to the textbox control.

So for this article first we will create a new asp.net application and add the below code into the page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm8.aspx.cs" Inherits="WebApplication7.WebForm8" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Convert DataTable To JSON Data In ASp.Net Using C#.Net</title>
</head>
<body>
    <form id="form1" runat="server">
        JSON Result
        <div>
            <asp:TextBox ID="txtJsonData" runat="server" Height="123px" TextMode="MultiLine"></asp:TextBox>
        </div>
    </form>
</body>
</html>

After this we will create a function which will provide data as datatable.

  /// <summary>
        /// You can access data from database into datatable
        /// </summary>
        /// <returns></returns>
        public DataTable GetDate()
        {
            DataTable dt = new DataTable();
            dt.Clear();
            dt.Columns.Add("Id");
            dt.Columns.Add("CountryName");
            dt.Columns.Add("Population");
            dt.Columns.Add("Code");

            DataRow dataRow1 = dt.NewRow();
            dataRow1["Id"] = 1;
            dataRow1["CountryName"] = "India";
            dataRow1["Population"] = "125 Cr";
            dataRow1["Code"] = "IN";
            dt.Rows.Add(dataRow1);

            DataRow dataRow2 = dt.NewRow();
            dataRow2["Id"] = 2;
            dataRow2["CountryName"] = "Pakistan";
            dataRow2["Population"] = "50 Cr";
            dataRow2["Code"] = "PK";
            dt.Rows.Add(dataRow2);

            DataRow dataRow3 = dt.NewRow();
            dataRow3["Id"] = 3;
            dataRow3["CountryName"] = "United States";
            dataRow3["Population"] = "25 Cr";
            dataRow3["Code"] = "US";
            dt.Rows.Add(dataRow3);

            return dt;
        }

In above code I have prepared a datatable. You can use code to get data from database.
Now we will create the function which will accept datatable as a parameter and convert the data into JSON string.

/// <summary>
        /// Converting DataTable into Json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string ConvertDataTableToJSON(DataTable dt)
        {
            JavaScriptSerializer jSonString = new JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return jSonString.Serialize(rows);
        }

In above function I have used JavaScriptSerializer to con vert the datatable into json result.  So here is the complete code.

using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Script.Serialization;

namespace WebApplication7
{
    public partial class WebForm8 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt = GetDate();
            string jsonString = ConvertDataTableToJSON(dt);
            //to display json data in taxtbox control
            txtJsonData.Text = jsonString;

        }
        /// <summary>
        /// You can access data from database into datatable
        /// </summary>
        /// <returns></returns>
        public DataTable GetDate()
        {
            DataTable dt = new DataTable();
            dt.Clear();
            dt.Columns.Add("Id");
            dt.Columns.Add("CountryName");
            dt.Columns.Add("Population");
            dt.Columns.Add("Code");

            DataRow dataRow1 = dt.NewRow();
            dataRow1["Id"] = 1;
            dataRow1["CountryName"] = "India";
            dataRow1["Population"] = "125 Cr";
            dataRow1["Code"] = "IN";
            dt.Rows.Add(dataRow1);

            DataRow dataRow2 = dt.NewRow();
            dataRow2["Id"] = 2;
            dataRow2["CountryName"] = "Pakistan";
            dataRow2["Population"] = "50 Cr";
            dataRow2["Code"] = "PK";
            dt.Rows.Add(dataRow2);

            DataRow dataRow3 = dt.NewRow();
            dataRow3["Id"] = 3;
            dataRow3["CountryName"] = "United States";
            dataRow3["Population"] = "25 Cr";
            dataRow3["Code"] = "US";
            dt.Rows.Add(dataRow3);

            return dt;
        }
        /// <summary>
        /// Converting DataTable into Json
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string ConvertDataTableToJSON(DataTable dt)
        {
            JavaScriptSerializer jSonString = new JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }
            return jSonString.Serialize(rows);
        }
    }
}

On page load I have converted the datatable into the json result and assign it to text box to display the final result. Now we have done run the application to check the output.


About the Author

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

Please let me know your view

Free Ebooks


About Us

We are the group of people who are expertise in different Microsoft technology like Asp.Net,MVC,C#.Net,VB.Net,Windows Application,WPF,jQuery,Javascript,HTML. This blog is designed to share the knowledge.

Contact Us

For writing article in this website please send request by your

GMAIL ID: dotnetpools@gmail.com
Email Id : contact@aspdotnet-pools.com

Bugs and Suggestions

As we all know that this website is for sharing knowledge and providing proper solution. So while reading the article is you find any bug or if you have any suggestion please mail us at contact@aspdotnet-pools.com.

Partners


Top jQuery Plugins

Global Classified : Connectseekers.com
© 2014
back to top