Skip to main content

Convert Dataset Datatable To Json Data Array in Asp.Net C#.Net & VB.Net or How To Use JavaScriptSerializer to Convert Datatable to Json Data Array

In this tutorial i am going to explain about how to convert dataset datatable to json data array in asp.net c#.net & vb.net or how to use JavaScriptSerializer to convert datatable to json data array


In my previous article i have explained about Highlight,Change Color Of Row On Mouseover In Grid View Using CSS - C#.Net ASP.Net VB.Net,Programmatically Group Gridview Column Headers,How To Convert JSON Data Into Html Table Using Javascript JQuery,Upload Multiple Files In Asp.Net C#.Net VB.Net / Maximum Request Length Exceeded,Change Row Color Of A Grid View Based On Particular Condition, and many articles in C#.Net,ASP.Net,VB.Net,Grid View,Javascript,jQuery,JSON and many other topics.

To start explaining about how to convert dataset datatable to json data array in asp.net c#.net & vb.net or how to use JavaScriptSerializer to convert datatable to json data array i am creating a new website in visual studio and in default.aspx file i have added a gridview control from the toolbox. And also i have added a div to display the json data. The gridview is used to bind gridview data and the div is used to bind the json array.The entire html markup is given below.

HTML Markup:

Datatable:

Equivalent JSON Data Array:


Now before proceeding to explain about how to convert dataset datatable to json data array in asp.net c#.net & vb.net or how to use JavaScriptSerializer to convert datatable to json data array please include below namespaces in your code behind file.

C#.Net:
using System.Data;
using System.Web.Script.Serialization;

VB.Net:
Imports System.Data
Imports System.Web.Script.Serialization

Now in the page load event i have created a datatable with some columns and inserted some sample records into that datatable. After that i have binded that datatable to gridview and then using the GetJson method defined in my code behind file i have converted the datatable into json dataarray. In the GetJson method the datatable is first converted into Dictionary object and then using Serialize method of JavaScriptSerializer class which is in System.Web.Script.Serialization namespace is used to serialize the dictionary object into json data array and then it is displayed in the div. The entire code is given below.

C#.Net:
protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Clear();
    dt.Columns.Add("Id");
    dt.Columns.Add("EmpName");
    dt.Columns.Add("DailyAllowance");
    dt.Columns.Add("Salary");

    //Creating object to to newrow to add to datatable
    DataRow NewRowObj = dt.NewRow();
    NewRowObj["Id"] = "1";
    NewRowObj["EmpName"] = "Kaviyarasan";
    NewRowObj["DailyAllowance"] = "500";
    NewRowObj["Salary"] = "52000";
    dt.Rows.Add(NewRowObj);

    NewRowObj = dt.NewRow();
    NewRowObj["Id"] = "2";
    NewRowObj["EmpName"] = "Ramkumar";
    NewRowObj["DailyAllowance"] = "600";
    NewRowObj["Salary"] = "16000";
    dt.Rows.Add(NewRowObj);

    NewRowObj = dt.NewRow();
    NewRowObj["Id"] = "3";
    NewRowObj["EmpName"] = "Kannadasan";
    NewRowObj["DailyAllowance"] = "700";
    NewRowObj["Salary"] = "37000";
    dt.Rows.Add(NewRowObj);

    NewRowObj = dt.NewRow();
    NewRowObj["Id"] = "4";
    NewRowObj["EmpName"] = "Xavier";
    NewRowObj["DailyAllowance"] = "800";
    NewRowObj["Salary"] = "82000";
    dt.Rows.Add(NewRowObj);

    NewRowObj = dt.NewRow();
    NewRowObj["Id"] = "5";
    NewRowObj["EmpName"] = "Murugan";
    NewRowObj["DailyAllowance"] = "1000";
    NewRowObj["Salary"] = "90000";
    dt.Rows.Add(NewRowObj);

    //To commit changes to datatable
    dt.AcceptChanges();

    //Binding Datatable to grid view
    grdDatatable.DataSource = dt;
    grdDatatable.DataBind();

    dvJasonData.InnerText = GetJson(dt);
        

}

//Method to convert Datatable to JSON array
public string GetJson(DataTable dt)
{
    JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
    List> DtRows =
        new List>();
    Dictionary newrow = null;

    //Code to loop each row in the datatable and add it to the dictionary object
    foreach (DataRow drow in dt.Rows)
    {
        newrow = new Dictionary();
        foreach (DataColumn col in dt.Columns)
        {
            newrow.Add(col.ColumnName.Trim(), drow[col]);
        }
        DtRows.Add(newrow);
    }

    //Serialising the dictionary object to produce json output
    return JSSerializer.Serialize(DtRows);
}

VB.Net:
Protected Sub Page_Load(sender As Object, e As EventArgs)
	Dim dt As New DataTable()
	dt.Clear()
	dt.Columns.Add("Id")
	dt.Columns.Add("EmpName")
	dt.Columns.Add("DailyAllowance")
	dt.Columns.Add("Salary")

	'Creating object to to newrow to add to datatable
	Dim NewRowObj As DataRow = dt.NewRow()
	NewRowObj("Id") = "1"
	NewRowObj("EmpName") = "Kaviyarasan"
	NewRowObj("DailyAllowance") = "500"
	NewRowObj("Salary") = "52000"
	dt.Rows.Add(NewRowObj)

	NewRowObj = dt.NewRow()
	NewRowObj("Id") = "2"
	NewRowObj("EmpName") = "Ramkumar"
	NewRowObj("DailyAllowance") = "600"
	NewRowObj("Salary") = "16000"
	dt.Rows.Add(NewRowObj)

	NewRowObj = dt.NewRow()
	NewRowObj("Id") = "3"
	NewRowObj("EmpName") = "Kannadasan"
	NewRowObj("DailyAllowance") = "700"
	NewRowObj("Salary") = "37000"
	dt.Rows.Add(NewRowObj)

	NewRowObj = dt.NewRow()
	NewRowObj("Id") = "4"
	NewRowObj("EmpName") = "Xavier"
	NewRowObj("DailyAllowance") = "800"
	NewRowObj("Salary") = "82000"
	dt.Rows.Add(NewRowObj)

	NewRowObj = dt.NewRow()
	NewRowObj("Id") = "5"
	NewRowObj("EmpName") = "Murugan"
	NewRowObj("DailyAllowance") = "1000"
	NewRowObj("Salary") = "90000"
	dt.Rows.Add(NewRowObj)

	'To commit changes to datatable
	dt.AcceptChanges()

	'Binding Datatable to grid view
	grdDatatable.DataSource = dt
	grdDatatable.DataBind()

	dvJasonData.InnerText = GetJson(dt)


End Sub

'Method to convert Datatable to JSON array
Public Function GetJson(dt As DataTable) As String
	Dim JSSerializer As New JavaScriptSerializer()
	Dim DtRows As New List(Of Dictionary(Of String, Object))()
	Dim newrow As Dictionary(Of String, Object) = Nothing

	'Code to loop each row in the datatable and add it to the dictionary object
	For Each drow As DataRow In dt.Rows
		newrow = New Dictionary(Of String, Object)()
		For Each col As DataColumn In dt.Columns
			newrow.Add(col.ColumnName.Trim(), drow(col))
		Next
		DtRows.Add(newrow)
	Next

	'Serialising the dictionary object to produce json output
	Return JSSerializer.Serialize(DtRows)
End Function

The output will look like the below screenshot.
Output of Convert Dataset Datatable To Json Data Array in Asp.Net C#.Net & VB.Net or How To Use JavaScriptSerializer to Convert Datatable to Json Data Array
Sourcecode of Convert Dataset Datatable To Json Data Array in Asp.Net C#.Net & VB.Net 

 Convert Dataset Datatable To Json Data Array in Asp.Net C#.Net & VB.Net or How To Use JavaScriptSerializer to Convert Datatable to Json Data Array

You May Also Like...

Comments

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     {         sb.Append( "Minus " );         inputNo = -inputNo;     }     string [] words0 = { "" , "One " ,

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw