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

By
Advertisement
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...

0 comments:

Post a Comment

Online Casino