Datatable to JSON

In this post I will explain you, how can we serialize Datatable to JSON. So that, it can easily pass to JavaScript to get the AJAX done.

First of all fill a Datatable with some results.

DataTable dt = new DataTable();
 
SqlConnection objSqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ToString());
objSqlCon.Open();
 
SqlDataAdapter objSqlDa = new SqlDataAdapter("select * from Production.Product", objSqlCon);
 
objSqlDa.Fill(dt);

Now create a String Builder object that will contain the JSON text and JavascriptSerializer which will serialize the output in JSON.

StringBuilder objSb = new StringBuilder();
JavaScriptSerializer objSer = new JavaScriptSerializer();

Now here we are going to iterate each row and column of data table and put all of them in Dictionary

Dictionary<string, object> resultMain = new Dictionary<string, object>();
int index = 0;
 
foreach (DataRow dr in dt.Rows)
{
    Dictionary<string, object> result = new Dictionary<string, object>();
 
    foreach (DataColumn dc in dt.Columns)
    {
        result.Add(dc.ColumnName, dr[dc].ToString());
    }
    resultMain.Add(index.ToString(), result);
    index++;
}

Notice that, I have created a new dictionary object for every row and finally put all of the dictionaries in Another dictionary I.E. resultMain.

In the end, I have simply Serialize the resultMain Dictionary to render JSON.

A complete post of utilizing Datatable  in JavaScript through AJAX is in the process, I will post that soon.

Published Saturday, May 16, 2009 5:53 PM by aghausman12
Filed under: , , , ,

Comments

# Datatable to JSON - Agha Usman

Saturday, May 16, 2009 7:58 AM by Datatable to JSON - Agha Usman

Pingback from  Datatable to JSON - Agha Usman

# re: Datatable to JSON

Monday, May 18, 2009 5:13 AM by Guy Harwood

why not just post one complete article?????

# re: Datatable to JSON

Monday, May 18, 2009 5:32 PM by aghausman12

@Harwood

Well, the main reason is time. Thank you very much for your time to read my post. I am in process of relocating my self to some other country. As soon as I get free, I  will post the complete one here

Leave a Comment

(required) 
(required) 
(optional)
(required)