Friday, 7 December 2012

Binding XML File to Gridview

Binding XML File to Gridview

In this post i will try to show you how one can bind easily XML file as a data source of GridView control. In the later section i will discuss how to bind XML file to a GridView control in run time.

Binding XML File in Design Mode:

To run this example at first add an XML file in your project & keep the name XMLFile.xml. Now modify the XML in the following way:

<?xml version="1.0" encoding="utf-8" ?>
< Id="0001" Title="Bind Dropdown List" Visit="985" Modified="Jan 01, 2009">
< Id="0002" Title="Event calendar" Visit="777" Modified="Feb 01, 2009">
< Id="0003" Title="Select all checkboxes" Visit="853" Modified="Mar 01, 2009">
< Id="0004" Title="Transfer data between" Visit="957" Modified="Apr 01, 2009">

Now add a GridView control in your page. The next step is to click the GridView control's smart tag and select:

Now click on browse button to set a Data File. Bydefault you found that our previously cretaed XMLFile.xml is selected. So just click OK--OK. Now run the project. Hope you will get the output page like below:



In Configuration data source wizard you saw that i keep blank Transform file & Xpath expression. You can set the Transform file value by your XSLT & use Xpath expression to bind the selected node from your XML file.

To bind an XML file runtime into a GridView using you can follow the below code:

protected void Page_Load(object sender, EventArgs e)


DataSet XMLDataSet;

string FilePath = Server.MapPath("Your XML File HERE");

XMLDataSet = new DataSet();

//Read the contents of the XML file into the DataSet


GridView1.DataSource = XMLDataSet.Tables[0].DefaultView;



1 comment:

  1. thanks Vishal, another excellent post as usual, could you ffer a tutorial on databinding with xml?


Thank You for Your Comments. We will get back to you soon.

back to top