2015-05-29 65 views
1
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(); 

我是c#和asp.net的新手,花了2個小時來修復這些代碼,但我仍然無法將項綁定到DataTable。請幫助我。Foreach使用C#和JSON將項綁定到Datatable使用C#和JSON

+1

您是否在調試器中查看dtInventory以確保它正在填充數據?當調試器停在此行時,DataTable如何看起來像這樣 this.rptInventory.DataSource = dtInventory; – Yuri

回答

0

它看起來像你沒有添加行到表中,所以當綁定發生時,沒有數據。這應該可以解決這個問題:

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

創建一個Inventory對象,並將json項添加到List<Inventory>而不是使用數據表。然後,您可以將List<Intentory>設置爲DataSource,rptInventory