Tuesday 11 February 2014

Bind asp.net Gridview to xml file using dataset

Bind gridview to xml file or read xml data and populate gridview in asp.net c# using dataset

This asp.net example is about binding xml file to asp.net gridview using c# with dataset lets create an example to implement asp.net gridview binding to xml file using dataset
Step 1: First let’s create a website. So start visual studio – File Menu—New – Website –Name the website and click ok. Then Add an xml by right clicking on solution--AddNewItem--select XML FIle--Name it as UserDetails.xml Inside the UserDetails.xml file add some user details tags and markups as shown below 


20fingers2brains Free Videos


 In the aspx designer page add the below code to add a gridview
   

            
                
                
                
                
            
        
    
Now lets create the code behind programming to bind gridview to an xml file This namespaces needs to be added to code behind .cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

        
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
      {
        BindGridToXML();
      }
 }
private void BindGridToXML()
{
        using (DataSet ds = new DataSet())
        {
                ds.ReadXml(Server.MapPath("~/UserDetails.xml"));
                gvUserDetails.DataSource = ds;
                gvUserDetails.DataBind();
        }
}

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
     gvUserDetails.PageIndex = e.NewPageIndex;
      this.BindGridToXML();
}

Complete C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace XMLExamples
{
    public partial class GridViewExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridToXML();
            }
        }

        private void BindGridToXML()
        {
            using (DataSet ds = new DataSet())
            {
                ds.ReadXml(Server.MapPath("~/UserDetails.xml"));
                gvUserDetails.DataSource = ds;
                gvUserDetails.DataBind();
            }
        }

       protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvUserDetails.PageIndex = e.NewPageIndex;
            this.BindGridToXML();
        }
    }
}
In this asp.net example we have learned how to bind xml file to a gridview

No comments:

Post a Comment