Thursday, 27 December 2012

how to bind json data to gridview in asp.net VB.NET

how to bind json data to gridview in asp.net VB.NET

  • Create a Web page

  • Add GridView to Web page

 <h1>GridView Json Object Binding</h1>
        <asp:GridView ID="GridView1" runat="server" EmptyDataText="No Data Found"></asp:GridView>
    </div>
  • Add a class Equivalent to  JSon Object retruning from 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


 
  • Deserialize JSON object to C# class in asp.net

        Private  Sub Deserialize_json_Object_and_Bind_GridView()
            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()
            json = "{\"SalesPerson\":" + json + "}"
            Dim w As wrapper = CType(New JavaScriptSerializer().Deserialize(json,Type.GetType(wrapper)), wrapper)

            GridView1.DataSource = w.salesperson
            GridView1.DataBind()
 End Sub
  •  Add following namespaces

Imports System.Net;
Imports System.IO;
Imports System.Web.Script.Serialization;
 
  • Call Deserialize and Binding method in Page_Load

       Protected  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
            System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("hi-IN")
            System.Threading.Thread.CurrentThread.CurrentUICulture = New System.Globalization.CultureInfo("hi-IN")
            Deserialize_jsob_Object_and_Bind_GridView()
  End Sub

  • Run the Page