How to bind a XML file to a GridView using Asp.net C#


Recently one of the most popular data source is XML. For simplicity developer wants to make an XML file since its easy to use in the Asp.net built in data controls like 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.

Focus Area:
1. Bind XML file in design mode
2. Bind XML file programetically


Bind 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" ?>
<
Article>
<
Asp.net Id="0001" Title="Bind Dropdown List" Visit="985" Modified="Jan 01, 2009">
</
Asp.net>
<
Asp.net Id="0002" Title="Event calendar" Visit="777" Modified="Feb 01, 2009">
</
Asp.net>
<
Asp.net Id="0003" Title="Select all checkboxes" Visit="853" Modified="Mar 01, 2009">
</
Asp.net>
<
Asp.net Id="0004" Title="Transfer data between" Visit="957" Modified="Apr 01, 2009">
</
Asp.net>
</
Article>

Now add a GridView control in your page. The next step is to click the GridView control's smart tag and select from the Choose Data Source dropdown list. This opens the Data Source Configuration Wizard, as shown in below:



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 Asp.net 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
XMLDataSet.ReadXml(FilePath);
GridView1.DataSource = XMLDataSet.Tables[0].DefaultView;
GridView1.DataBind();
}

4 comments:

kanthu said...

good code

Information said...

Thank Q For Your Encouragement

Anonymous said...

populate gridview control with xml data

career point said...

Thanks for ur code.one question
What is the return type of XMLDataSet.ReadXml(FilePath);?

Post a Comment