how to bind json data to datagrid in wpf VB.NET
- Create a WPF Project using VB.NET 4.0/4.5
- Add datagrid to XAML
- Add a class equivalent to JSON object
- Deserialize JSON object to class in WPFVB.NET
- 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 Property salesperson() As List<SalesPerson>
End Property
End Class
Public Class SalesPerson
Public Property id() As String
End Property
Public Property rowOrder() As Integer
End Property
Public Property BusinessEntityID() As int?
End Property
Public Property Bonus() As decimal?
End Property
Public Property CommissionPct() As decimal?
End Property
Public Property SalesLastYear() As decimal?
End Property
Public Property SalesYTD() As decimal?
End Property
Public Property TerritoryID() As int?
End Property
Public Property ModifiedDate() As DateTime?
End Property
End Class
Step 4) Deserialize JSON data to VB.NET class
Dim req As WebRequest = WebRequest.Create("http://localhost:3054/RestWCF.svc/GetDataTableJson")
req.ContentType = "application/json"
Dim resp As WebResponse = req.GetResponse()
Dim stream As Stream = resp.GetResponseStream()
Dim re As StreamReader = New StreamReader(stream)
Dim json As String = re.ReadToEnd()
'Note: WCF returns anonymous array list , so we need to append class name manually. In this case SalesPerson is the class name.
json = "{\"SalesPerson\":" + json + "}"
Dim w As wrapper = CType(New JavaScriptSerializer().Deserialize(json,Type.GetType(wrapper)), wrapper)
Step 5) Bind it to DataGrid
datagrid1.ItemsSource = w.salesperson;
Step 6) Add namespaces
Imports System.IO;
Imports System.Net;
Imports System.Web.Script.Serialization;
Step 7) Run the Application
what if you do not know the structure ahead of time
ReplyDelete