Search code examples
c#asp.netjson.netrepeater

Foreach bind items to Datatable with C# and JSON


    DataTable dtInventory = new DataTable();
    dtInventory.Columns.Add("ItemID", typeof(string));
    dtInventory.Columns.Add("ItemImageUrl", typeof(string));
    dtInventory.Columns.Add("ItemName", typeof(string));
    dtInventory.Columns.Add("Tradeable", typeof(string));

    string json = new WebClient().DownloadString("storeJSON.txt");
    JToken jsonInventory = JToken.Parse(json);
    JObject jsonItemData = jsonInventory["StoreData"].Value<JObject>();

    foreach (JProperty jItemID in jsonItemData.Properties())
    {
        string sItemID = jItemID.Name.Trim().ToString();

        for (int i = 0; i < jsonItemData.Count; i++)
        {
            DataRow dtRow = dtInventory.NewRow();
            dtRow["ItemID"] = sItemID.ToString();
            dtRow["ItemImageUrl"] = jsonItemData[sItemID]["icon_url"].ToString();
            dtRow["ItemName"] = jsonItemData[sItemID]["market_name"].ToString();
            dtRow["Tradeable"] = jsonItemData[sItemID]["tradable"].ToString();
        }
    }
    this.rptInventory.DataSource = dtInventory;
    this.rptInventory.DataBind();

I'm newbie to c# and asp.net and it took me 2 hours to fix these codes but I still can't bind items to DataTable. Please help me out.


Solution

  • It looks like you're not adding the rows to the table so when the binding takes place, there's no data. This should fix that problem:

    for (int i = 0; i < jsonItemData.Count; i++) {
              DataRow dtRow = dtInventory.NewRow();
              dtRow["ItemID"] = sItemID.ToString();
              dtRow["ItemImageUrl"] = jsonItemData[sItemID]["icon_url"].ToString();
              dtRow["ItemName"] = jsonItemData[sItemID]["market_name"].ToString();
              dtRow["Tradeable"] = jsonItemData[sItemID]["tradable"].ToString();
    
              dtInventory.Rows.Add(dtRow); //this line adds the row to the table
    }