maltman maltman - 4 months ago 15
JSON Question

Bind JSON string to Gridview

I am trying to take output from my JSON and add it to a Gridview. I have created a DataTable to store the data and I am trying to bind that to my Gridview. When I debug, I see each value being added to the DataTable. By the end, there are 10 rows. But nothing binds to the Gridview in the end. Let me know if I need to add anything else to help.

var data = JsonConvert.DeserializeObject<RootObject>(result);

DataTable dt = new DataTable();
dt.Columns.Add("Site", typeof(string));
dt.Columns.Add("Status", typeof(int));

foreach (var item in data.records)
{
string site = item.name;
string status = item.data;
DataRow row = dt.NewRow();
row[0] = site;
row[1] = status;
dt.Rows.Add(row);
}

GridView1.DataSource = dt;
GridView1.DataBind();


JSON Output. Just the records portion.

{
"kind":"internal",
"name":"SplashPageToggle_dg",
"fullPath":"SplashPageToggle_dg",
"generation":1255326,
"selfLink":"https://link",
"type":"stri ng",
"records":[
{
"name":"enable_app1",
"data":"0"
},
{
"name":"enable_app2",
"da ta":"0"
},
{
"name":"enable_app3",
"data":"0"
},
{
"name":"enable_app4",
"data":"0"
},
{
"name":"enable_app5",
"data":"0"
},
{
"name":"enable_app6",
"data":"1"
},
{
"name":"enable_app7",
"data":"0"
},
{
"name":"enable_app8",
"data":"0"
},
{
"name":"enable_app9",
"data":"0"
},
{
"name":"enable_app10",
"data":"0"
}
]
}


Gridview code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Visible="true">
<Columns>
<asp:BoundField HeaderText="Site" />
<asp:BoundField HeaderText="Status" />
</Columns>
</asp:GridView>

Answer

If the datatable has rows, then you are able to retrieve data from json. You should check what is wrong with the gridview HTML code. You could have copy paste from some other page and the field values are all wrong. It would be helpful if you post the gridview code.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Visible="true">
    <Columns>
        <asp:BoundField DataField="site" HeaderText="Site" />
        <asp:BoundField DataField="status" HeaderText="Status" />
    </Columns>
</asp:GridView>
Comments