Convert DataTabel to Json in Asp.net

 Convert DataTabel to Json in Asp.net




protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = DtTable();
        string change = ReturnJSON(dt);
       
    }

public DataTable DtTable()
    {
        DataTable table = new DataTable() { TableName = "Customer" };

        DataColumn keyColumn = table.Columns.Add("Id", typeof(System.Int32));
        table.Columns.Add("Name", typeof(System.String));
        table.Columns.Add("Address", typeof(System.String));

        table.PrimaryKey = new DataColumn[] { keyColumn };

        table.Rows.Add(new object[] { 1, "Customer 1", "Address1" });
        table.Rows.Add(new object[] { 2, "Customer 2", "Address2" });
        table.Rows.Add(new object[] { 3, "Customer 3", "Address3" });
        table.Rows.Add(new object[] { 4, "Customer 4", "Address4" });
        table.Rows.Add(new object[] { 5, "Customer 5", "Address5" });

        table.AcceptChanges();
        return table;
    }



public string ReturnJSON(DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.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);

}
string ret = serializer.Serialize(rows);

return ret;

}

Comments

Popular posts from this blog

Create and save QR code in asp.net with C#

Change text of RadGrid Header Dynamically

Telerik Radwindow Open on Button Click