Follow by Email

Tuesday, 23 July 2013

How to convert datatable into JSON in C#

string query="select * from tableName";

SqlCommand cmd=new SqlCommand(query,conn);

SqlDataAdapter da=new SqlDataAdapter(cmd);

 Datatable dt;

da.Fill(dt);

        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        var rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row = null;

        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);
        }



        var groupDtaa = "{'groups':" + serializer.Serialize(rows)+"}";

        Response.Write(groupDtaa);

2 comments:

Ayesha Sharma said...

very nice. Thanks.

Take a look into this article http://www.etechpulse.com/2012/09/convert-datatable-to-json-in-aspnet.html

Abhinav Ranjan Sinha said...

Thanks Ayesha

Post a Comment


                                                            

 
Design by Abhinav Ranjan Sinha