将JSON字符串绑定到Gridview

时间:2016-07-12 20:05:36

标签: c# json gridview json.net

我正在尝试从我的JSON获取输出并将其添加到Gridview。我创建了一个DataTable来存储数据,我试图将它绑定到我的Gridview。当我调试时,我看到每个值都被添加到DataTable中。到最后,有10行。但最终没有什么能与Gridview绑定。如果我需要添加其他任何内容来帮助我。

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输出。只是记录部分。

{
    "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代码

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

1 个答案:

答案 0 :(得分:3)

如果数据表有行,那么您就可以从json中检索数据。您应该检查gridview HTML代码有什么问题。您可以从其他页面复制粘贴,并且字段值都是错误的。如果你发布gridview代码会很有帮助。

<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>