convert and bind JSON to asp.net gridview

18,515

Solution 1

I'd solve it like this:

First Step: Download JSON.net

Second Step:

in your CS page

using Newtonsoft.Json;

public DataTable DerializeDataTable()
{       
    string json = data; //"data" should contain your JSON 
    var table = JsonConvert.DeserializeObject<DataTable>(json);
    return table;
}

now use the function as a datasource to your gridview

protected void btn1_Click(object sender, EventArgs e)
{
GridView1.DataSource = DerializeDataTable();
GridView1.DataBind();
}

hope this helps

Solution 2

See this question about how to convert your JSON code into a DataSet object (which plays nicely with GridView objects).

From there, you can assign the DataSource property of your GridView to your converted DataSet and then run the DataBind() method.

I personally prefer to use code behind approach when actually rendering the data by using templates and the RowDataBound event to format my data.

Share:
18,515
user3565664
Author by

user3565664

Updated on June 04, 2022

Comments

  • user3565664
    user3565664 almost 2 years

    I have the following JSON

    [{"time":"11:28","message":"user1: hi"},{"time":"11:28","message":"user2: hi to you"}] 
    

    it was very easy to serialize from a database table using C#. i used the following function to serialize

    public String ConvertDataTableTojSonString(DataTable dataTable)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer =
               new System.Web.Script.Serialization.JavaScriptSerializer();
    
        List<Dictionary<String, Object>> tableRows = new List<Dictionary<String, Object>>();
    
        Dictionary<String, Object> row;
    
        foreach (DataRow dr in dataTable.Rows)
        {
            row = new Dictionary<String, Object>();
            foreach (DataColumn col in dataTable.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            tableRows.Add(row);
        }
        return serializer.Serialize(tableRows);
    }
    

    i thought it might be some error in the JSON it self, but i tested it in http://jsonlint.org/ and it was valid However i tried and searched a lot to convert it back to any format that can bind to asp.net gridview. any ideas?