how to bind json data to datagrid in wpf C#
- Create a WPF Project using C# 4.0/4.5
- Add datagrid to XAML
- Add a class equivalent to JSON object
- Deserialize JSON object to class in WPF C#
- Bind list to datagrid.
- run the application.
Step 3) Adding class Equivalent to JSON object returning from WCF See this article
public class wrapper
{
public List<SalesPerson> salesperson { get; set; }
}
public class SalesPerson
{
public String id { get; set; }
public int rowOrder { get; set; }
public int? BusinessEntityID { get; set; }
public decimal? Bonus { get; set; }
public decimal? CommissionPct { get; set; }
public decimal? SalesLastYear { get; set; }
public decimal? SalesYTD { get; set; }
public int? TerritoryID { get; set; }
public DateTime? ModifiedDate { get; set; }
}
Step 4) Deserialize JSON data to C# class
WebRequest req = WebRequest.Create("http://localhost:3054/RestWCF.svc/GetDataTableJson");
req.ContentType = "application/json";
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader re = new StreamReader(stream);
String json = re.ReadToEnd();
json = "{\"SalesPerson\":" + json + "}";
wrapper w = (wrapper)new JavaScriptSerializer().Deserialize(json, typeof(wrapper));
Step 5) Bind it to DataGrid
datagrid1.ItemsSource = w.salesperson;
Step 6) Add namespaces
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
Step 7) Run the Application
How would with MVVM architecture?
ReplyDelete