use this code :
Out Put :
used namespace
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data;
public string DataTableToJSON()
{
DataTable dtCustomer = new DataTable();
dtCustomer.Columns.AddRange(
new DataColumn[]
{ new DataColumn("ID", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("City", typeof(string))
}
);
// Add value to the related column
dtCustomer.Rows.Add(1001, "PABITRA BEHERA","Bhubaneswar");
dtCustomer.Rows.Add(1002, "Arya Kumar", "Cuttack");
dtCustomer.Rows.Add(1003, "Mr Roket(Braja)", "Nayagard");
dtCustomer.Rows.Add(1004, "Mr Trupti", "Bhadrak");
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in dtCustomer.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in dtCustomer.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
Call the function in page load
i.e.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write(DataTableToJSON());
}
}
Out Put :
used namespace
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data;
{
DataTable dtCustomer = new DataTable();
dtCustomer.Columns.AddRange(
new DataColumn[]
{ new DataColumn("ID", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("City", typeof(string))
}
);
// Add value to the related column
dtCustomer.Rows.Add(1001, "PABITRA BEHERA","Bhubaneswar");
dtCustomer.Rows.Add(1002, "Arya Kumar", "Cuttack");
dtCustomer.Rows.Add(1003, "Mr Roket(Braja)", "Nayagard");
dtCustomer.Rows.Add(1004, "Mr Trupti", "Bhadrak");
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in dtCustomer.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in dtCustomer.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
Call the function in page load
i.e.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write(DataTableToJSON());
}
}
No comments:
Post a Comment