Thursday, 27 December 2012

how to bind json data to gridview in asp.net C#

how to bind json data to gridview in asp.net C#


  • 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 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; }
    }
 
  • Deserialize JSON object to C# class in asp.net

        void Deserialize_json_Object_and_Bind_GridView()
        {
            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));

            GridView1.DataSource = w.salesperson;
            GridView1.DataBind();
        }
  •  Add following namespaces

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

         protected void Page_Load(object sender, EventArgs e)
        {
            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();
        }

  • Run the Page